summaryrefslogtreecommitdiff
path: root/src/core/iregex-regexh.c
blob: 897eb7e2b4d4da05e57b2a0a0505072c5743ba35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "iregex.h"

Regex *
i_regex_new (const gchar *pattern,
             GRegexCompileFlags compile_options,
             GRegexMatchFlags match_options,
             GError **error)
{
	Regex *regex;
	char *errbuf;
	int cflags;
	int errcode, errbuf_len;

	regex = g_new0(Regex, 1);
	cflags = REG_EXTENDED;
	if (compile_options & G_REGEX_CASELESS)
		cflags |= REG_ICASE;
	if (compile_options & G_REGEX_MULTILINE)
		cflags |= REG_NEWLINE;
	if (match_options & G_REGEX_MATCH_NOTBOL)
		cflags |= REG_NOTBOL;
	if (match_options & G_REGEX_MATCH_NOTEOL)
		cflags |= REG_NOTEOL;

	errcode = regcomp(regex, pattern, cflags);
	if (errcode != 0) {
		errbuf_len = regerror(errcode, regex, 0, 0);
		errbuf = g_malloc(errbuf_len);
		regerror(errcode, regex, errbuf, errbuf_len);
		g_set_error(error, G_REGEX_ERROR, errcode, "%s", errbuf);
		g_free(errbuf);
		g_free(regex);
		return NULL;
	} else {
		return regex;
	}
}

void
i_regex_unref (Regex *regex)
{
	regfree(regex);
	g_free(regex);
}

gboolean
i_regex_match (const Regex *regex,
               const gchar *string,
               GRegexMatchFlags match_options,
               MatchInfo **match_info)
{
	int groups;
	int eflags;

	g_return_val_if_fail(regex != NULL, FALSE);

	if (match_info != NULL) {
		groups = 1 + regex->re_nsub;
		*match_info = g_new0(MatchInfo, groups);
	} else {
		groups = 0;
	}

	eflags = 0;
	if (match_options & G_REGEX_MATCH_NOTBOL)
		eflags |= REG_NOTBOL;
	if (match_options & G_REGEX_MATCH_NOTEOL)
		eflags |= REG_NOTEOL;

	return regexec(regex, string, groups, groups ? *match_info : NULL, eflags) == 0;
}

gboolean
i_match_info_fetch_pos (const MatchInfo *match_info,
                        gint match_num,
                        gint *start_pos,
                        gint *end_pos)
{
	if (start_pos != NULL)
		*start_pos = match_info[match_num].rm_so;
	if (end_pos != NULL)
		*end_pos = match_info[match_num].rm_eo;

	return TRUE;
}

gboolean
i_match_info_matches (const MatchInfo *match_info)
{
	g_return_val_if_fail(match_info != NULL, FALSE);

	return match_info[0].rm_so != -1;
}

void
i_match_info_free (MatchInfo *match_info)
{
	g_free(match_info);
}