1 /* GRegex -- regular expression API wrapper around PCRE.
3 * Copyright (C) 1999, 2000 Scott Wimer
4 * Copyright (C) 2004, Matthias Clasen <mclasen@redhat.com>
5 * Copyright (C) 2005 - 2007, Marco Barisione <marco@barisione.org>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26 #ifdef USE_SYSTEM_PCRE
29 #include "pcre/pcre.h"
36 #include "gmessages.h"
37 #include "gstrfuncs.h"
43 * @title: Perl-compatible regular expressions
44 * @short_description: matches strings against regular expressions
45 * @see_also: [Regular expression syntax][glib-regex-syntax]
47 * The g_regex_*() functions implement regular
48 * expression pattern matching using syntax and semantics similar to
49 * Perl regular expression.
51 * Some functions accept a @start_position argument, setting it differs
52 * from just passing over a shortened string and setting #G_REGEX_MATCH_NOTBOL
53 * in the case of a pattern that begins with any kind of lookbehind assertion.
54 * For example, consider the pattern "\Biss\B" which finds occurrences of "iss"
55 * in the middle of words. ("\B" matches only if the current position in the
56 * subject is not a word boundary.) When applied to the string "Mississipi"
57 * from the fourth byte, namely "issipi", it does not match, because "\B" is
58 * always false at the start of the subject, which is deemed to be a word
59 * boundary. However, if the entire string is passed , but with
60 * @start_position set to 4, it finds the second occurrence of "iss" because
61 * it is able to look behind the starting point to discover that it is
62 * preceded by a letter.
64 * Note that, unless you set the #G_REGEX_RAW flag, all the strings passed
65 * to these functions must be encoded in UTF-8. The lengths and the positions
66 * inside the strings are in bytes and not in characters, so, for instance,
67 * "\xc3\xa0" (i.e. "à") is two bytes long but it is treated as a
68 * single character. If you set #G_REGEX_RAW the strings can be non-valid
69 * UTF-8 strings and a byte is treated as a character, so "\xc3\xa0" is two
70 * bytes and two characters long.
72 * When matching a pattern, "\n" matches only against a "\n" character in
73 * the string, and "\r" matches only a "\r" character. To match any newline
74 * sequence use "\R". This particular group matches either the two-character
75 * sequence CR + LF ("\r\n"), or one of the single characters LF (linefeed,
76 * U+000A, "\n"), VT vertical tab, U+000B, "\v"), FF (formfeed, U+000C, "\f"),
77 * CR (carriage return, U+000D, "\r"), NEL (next line, U+0085), LS (line
78 * separator, U+2028), or PS (paragraph separator, U+2029).
80 * The behaviour of the dot, circumflex, and dollar metacharacters are
81 * affected by newline characters, the default is to recognize any newline
82 * character (the same characters recognized by "\R"). This can be changed
83 * with #G_REGEX_NEWLINE_CR, #G_REGEX_NEWLINE_LF and #G_REGEX_NEWLINE_CRLF
84 * compile options, and with #G_REGEX_MATCH_NEWLINE_ANY,
85 * #G_REGEX_MATCH_NEWLINE_CR, #G_REGEX_MATCH_NEWLINE_LF and
86 * #G_REGEX_MATCH_NEWLINE_CRLF match options. These settings are also
87 * relevant when compiling a pattern if #G_REGEX_EXTENDED is set, and an
88 * unescaped "#" outside a character class is encountered. This indicates
89 * a comment that lasts until after the next newline.
91 * When setting the %G_REGEX_JAVASCRIPT_COMPAT flag, pattern syntax and pattern
92 * matching is changed to be compatible with the way that regular expressions
93 * work in JavaScript. More precisely, a lonely ']' character in the pattern
94 * is a syntax error; the '\x' escape only allows 0 to 2 hexadecimal digits, and
95 * you must use the '\u' escape sequence with 4 hex digits to specify a unicode
96 * codepoint instead of '\x' or 'x{....}'. If '\x' or '\u' are not followed by
97 * the specified number of hex digits, they match 'x' and 'u' literally; also
98 * '\U' always matches 'U' instead of being an error in the pattern. Finally,
99 * pattern matching is modified so that back references to an unset subpattern
100 * group produces a match with the empty string instead of an error. See
101 * pcreapi(3) for more information.
103 * Creating and manipulating the same #GRegex structure from different
104 * threads is not a problem as #GRegex does not modify its internal
105 * state between creation and destruction, on the other hand #GMatchInfo
108 * The regular expressions low-level functionalities are obtained through
110 * [PCRE](http://www.pcre.org/)
111 * library written by Philip Hazel.
114 /* Mask of all the possible values for GRegexCompileFlags. */
115 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
116 G_REGEX_MULTILINE | \
120 G_REGEX_DOLLAR_ENDONLY | \
123 G_REGEX_NO_AUTO_CAPTURE | \
125 G_REGEX_FIRSTLINE | \
127 G_REGEX_NEWLINE_CR | \
128 G_REGEX_NEWLINE_LF | \
129 G_REGEX_NEWLINE_CRLF | \
130 G_REGEX_NEWLINE_ANYCRLF | \
131 G_REGEX_BSR_ANYCRLF | \
132 G_REGEX_JAVASCRIPT_COMPAT)
134 /* Mask of all GRegexCompileFlags values that are (not) passed trough to PCRE */
135 #define G_REGEX_COMPILE_PCRE_MASK (G_REGEX_COMPILE_MASK & ~G_REGEX_COMPILE_NONPCRE_MASK)
136 #define G_REGEX_COMPILE_NONPCRE_MASK (G_REGEX_RAW | \
139 /* Mask of all the possible values for GRegexMatchFlags. */
140 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
141 G_REGEX_MATCH_NOTBOL | \
142 G_REGEX_MATCH_NOTEOL | \
143 G_REGEX_MATCH_NOTEMPTY | \
144 G_REGEX_MATCH_PARTIAL | \
145 G_REGEX_MATCH_NEWLINE_CR | \
146 G_REGEX_MATCH_NEWLINE_LF | \
147 G_REGEX_MATCH_NEWLINE_CRLF | \
148 G_REGEX_MATCH_NEWLINE_ANY | \
149 G_REGEX_MATCH_NEWLINE_ANYCRLF | \
150 G_REGEX_MATCH_BSR_ANYCRLF | \
151 G_REGEX_MATCH_BSR_ANY | \
152 G_REGEX_MATCH_PARTIAL_SOFT | \
153 G_REGEX_MATCH_PARTIAL_HARD | \
154 G_REGEX_MATCH_NOTEMPTY_ATSTART)
156 /* we rely on these flags having the same values */
157 G_STATIC_ASSERT (G_REGEX_CASELESS == PCRE_CASELESS);
158 G_STATIC_ASSERT (G_REGEX_MULTILINE == PCRE_MULTILINE);
159 G_STATIC_ASSERT (G_REGEX_DOTALL == PCRE_DOTALL);
160 G_STATIC_ASSERT (G_REGEX_EXTENDED == PCRE_EXTENDED);
161 G_STATIC_ASSERT (G_REGEX_ANCHORED == PCRE_ANCHORED);
162 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY == PCRE_DOLLAR_ENDONLY);
163 G_STATIC_ASSERT (G_REGEX_UNGREEDY == PCRE_UNGREEDY);
164 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE == PCRE_NO_AUTO_CAPTURE);
165 G_STATIC_ASSERT (G_REGEX_FIRSTLINE == PCRE_FIRSTLINE);
166 G_STATIC_ASSERT (G_REGEX_DUPNAMES == PCRE_DUPNAMES);
167 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR == PCRE_NEWLINE_CR);
168 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF == PCRE_NEWLINE_LF);
169 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
170 G_STATIC_ASSERT (G_REGEX_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
171 G_STATIC_ASSERT (G_REGEX_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
172 G_STATIC_ASSERT (G_REGEX_JAVASCRIPT_COMPAT == PCRE_JAVASCRIPT_COMPAT);
174 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED == PCRE_ANCHORED);
175 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL == PCRE_NOTBOL);
176 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL == PCRE_NOTEOL);
177 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY == PCRE_NOTEMPTY);
178 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL == PCRE_PARTIAL);
179 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR == PCRE_NEWLINE_CR);
180 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF == PCRE_NEWLINE_LF);
181 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
182 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY == PCRE_NEWLINE_ANY);
183 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
184 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
185 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANY == PCRE_BSR_UNICODE);
186 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL_SOFT == PCRE_PARTIAL_SOFT);
187 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL_HARD == PCRE_PARTIAL_HARD);
188 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY_ATSTART == PCRE_NOTEMPTY_ATSTART);
190 /* These PCRE flags are unused or not exposed publically in GRegexFlags, so
191 * it should be ok to reuse them for different things.
193 G_STATIC_ASSERT (G_REGEX_OPTIMIZE == PCRE_NO_UTF8_CHECK);
194 G_STATIC_ASSERT (G_REGEX_RAW == PCRE_UTF8);
196 /* if the string is in UTF-8 use g_utf8_ functions, else use
198 #define NEXT_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
200 g_utf8_next_char (s))
201 #define PREV_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
203 g_utf8_prev_char (s))
207 volatile gint ref_count; /* the ref count */
208 GRegex *regex; /* the regex */
209 GRegexMatchFlags match_opts; /* options used at match time on the regex */
210 gint matches; /* number of matching sub patterns */
211 gint pos; /* position in the string where last match left off */
212 gint n_offsets; /* number of offsets */
213 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
214 gint *workspace; /* workspace for pcre_dfa_exec() */
215 gint n_workspace; /* number of workspace elements */
216 const gchar *string; /* string passed to the match function */
217 gssize string_len; /* length of string */
222 volatile gint ref_count; /* the ref count for the immutable part */
223 gchar *pattern; /* the pattern */
224 pcre *pcre_re; /* compiled form of the pattern */
225 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
226 GRegexMatchFlags match_opts; /* options used at match time on the regex */
227 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
230 /* TRUE if ret is an error code, FALSE otherwise. */
231 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
233 typedef struct _InterpolationData InterpolationData;
234 static gboolean interpolation_list_needs_match (GList *list);
235 static gboolean interpolate_replacement (const GMatchInfo *match_info,
238 static GList *split_replacement (const gchar *replacement,
240 static void free_interpolation_data (InterpolationData *data);
244 match_error (gint errcode)
248 case PCRE_ERROR_NOMATCH:
251 case PCRE_ERROR_NULL:
252 /* NULL argument, this should not happen in GRegex */
253 g_warning ("A NULL argument was passed to PCRE");
255 case PCRE_ERROR_BADOPTION:
256 return "bad options";
257 case PCRE_ERROR_BADMAGIC:
258 return _("corrupted object");
259 case PCRE_ERROR_UNKNOWN_OPCODE:
260 return N_("internal error or corrupted object");
261 case PCRE_ERROR_NOMEMORY:
262 return _("out of memory");
263 case PCRE_ERROR_NOSUBSTRING:
264 /* not used by pcre_exec() */
266 case PCRE_ERROR_MATCHLIMIT:
267 return _("backtracking limit reached");
268 case PCRE_ERROR_CALLOUT:
269 /* callouts are not implemented */
271 case PCRE_ERROR_BADUTF8:
272 case PCRE_ERROR_BADUTF8_OFFSET:
273 /* we do not check if strings are valid */
275 case PCRE_ERROR_PARTIAL:
278 case PCRE_ERROR_BADPARTIAL:
279 return _("the pattern contains items not supported for partial matching");
280 case PCRE_ERROR_INTERNAL:
281 return _("internal error");
282 case PCRE_ERROR_BADCOUNT:
283 /* negative ovecsize, this should not happen in GRegex */
284 g_warning ("A negative ovecsize was passed to PCRE");
286 case PCRE_ERROR_DFA_UITEM:
287 return _("the pattern contains items not supported for partial matching");
288 case PCRE_ERROR_DFA_UCOND:
289 return _("back references as conditions are not supported for partial matching");
290 case PCRE_ERROR_DFA_UMLIMIT:
291 /* the match_field field is not used in GRegex */
293 case PCRE_ERROR_DFA_WSSIZE:
294 /* handled expanding the workspace */
296 case PCRE_ERROR_DFA_RECURSE:
297 case PCRE_ERROR_RECURSIONLIMIT:
298 return _("recursion limit reached");
299 case PCRE_ERROR_BADNEWLINE:
300 return _("invalid combination of newline flags");
301 case PCRE_ERROR_BADOFFSET:
302 return _("bad offset");
303 case PCRE_ERROR_SHORTUTF8:
304 return _("short utf8");
305 case PCRE_ERROR_RECURSELOOP:
306 return _("recursion loop");
310 return _("unknown error");
314 translate_compile_error (gint *errcode, const gchar **errmsg)
316 /* Compile errors are created adding 100 to the error code returned
318 * If errcode is known we put the translatable error message in
319 * erromsg. If errcode is unknown we put the generic
320 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
321 * untranslated error message returned by PCRE.
322 * Note that there can be more PCRE errors with the same GRegexError
323 * and that some PCRE errors are useless for us.
329 case G_REGEX_ERROR_STRAY_BACKSLASH:
330 *errmsg = _("\\ at end of pattern");
332 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
333 *errmsg = _("\\c at end of pattern");
335 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
336 *errmsg = _("unrecognized character following \\");
338 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
339 *errmsg = _("numbers out of order in {} quantifier");
341 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
342 *errmsg = _("number too big in {} quantifier");
344 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
345 *errmsg = _("missing terminating ] for character class");
347 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
348 *errmsg = _("invalid escape sequence in character class");
350 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
351 *errmsg = _("range out of order in character class");
353 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
354 *errmsg = _("nothing to repeat");
356 case 111: /* internal error: unexpected repeat */
357 *errcode = G_REGEX_ERROR_INTERNAL;
358 *errmsg = _("unexpected repeat");
360 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
361 *errmsg = _("unrecognized character after (? or (?-");
363 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
364 *errmsg = _("POSIX named classes are supported only within a class");
366 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
367 *errmsg = _("missing terminating )");
369 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
370 *errmsg = _("reference to non-existent subpattern");
372 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
373 *errmsg = _("missing ) after comment");
375 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
376 *errmsg = _("regular expression is too large");
378 case G_REGEX_ERROR_MEMORY_ERROR:
379 *errmsg = _("failed to get memory");
381 case 122: /* unmatched parentheses */
382 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
383 *errmsg = _(") without opening (");
385 case 123: /* internal error: code overflow */
386 *errcode = G_REGEX_ERROR_INTERNAL;
387 *errmsg = _("code overflow");
389 case 124: /* "unrecognized character after (?<\0 */
390 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
391 *errmsg = _("unrecognized character after (?<");
393 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
394 *errmsg = _("lookbehind assertion is not fixed length");
396 case G_REGEX_ERROR_MALFORMED_CONDITION:
397 *errmsg = _("malformed number or name after (?(");
399 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
400 *errmsg = _("conditional group contains more than two branches");
402 case G_REGEX_ERROR_ASSERTION_EXPECTED:
403 *errmsg = _("assertion expected after (?(");
406 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
407 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
408 * sequences here, '(?-54' would be an example for the second group.
410 *errmsg = _("(?R or (?[+-]digits must be followed by )");
412 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
413 *errmsg = _("unknown POSIX class name");
415 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
416 *errmsg = _("POSIX collating elements are not supported");
418 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
419 *errmsg = _("character value in \\x{...} sequence is too large");
421 case G_REGEX_ERROR_INVALID_CONDITION:
422 *errmsg = _("invalid condition (?(0)");
424 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
425 *errmsg = _("\\C not allowed in lookbehind assertion");
427 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
428 /* A number of Perl escapes are not handled by PCRE.
429 * Therefore it explicitly raises ERR37.
431 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
432 *errmsg = _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
434 case G_REGEX_ERROR_INFINITE_LOOP:
435 *errmsg = _("recursive call could loop indefinitely");
437 case 141: /* unrecognized character after (?P\0 */
438 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
439 *errmsg = _("unrecognized character after (?P");
441 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
442 *errmsg = _("missing terminator in subpattern name");
444 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
445 *errmsg = _("two named subpatterns have the same name");
447 case G_REGEX_ERROR_MALFORMED_PROPERTY:
448 *errmsg = _("malformed \\P or \\p sequence");
450 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
451 *errmsg = _("unknown property name after \\P or \\p");
453 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
454 *errmsg = _("subpattern name is too long (maximum 32 characters)");
456 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
457 *errmsg = _("too many named subpatterns (maximum 10,000)");
459 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
460 *errmsg = _("octal value is greater than \\377");
462 case 152: /* internal error: overran compiling workspace */
463 *errcode = G_REGEX_ERROR_INTERNAL;
464 *errmsg = _("overran compiling workspace");
466 case 153: /* internal error: previously-checked referenced subpattern not found */
467 *errcode = G_REGEX_ERROR_INTERNAL;
468 *errmsg = _("previously-checked referenced subpattern not found");
470 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
471 *errmsg = _("DEFINE group contains more than one branch");
473 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
474 *errmsg = _("inconsistent NEWLINE options");
476 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
477 *errmsg = _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
478 "number, or by a plain number");
480 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE:
481 *errmsg = _("a numbered reference must not be zero");
483 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
484 *errmsg = _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
486 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB:
487 *errmsg = _("(*VERB) not recognized");
489 case G_REGEX_ERROR_NUMBER_TOO_BIG:
490 *errmsg = _("number is too big");
492 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME:
493 *errmsg = _("missing subpattern name after (?&");
495 case G_REGEX_ERROR_MISSING_DIGIT:
496 *errmsg = _("digit expected after (?+");
498 case G_REGEX_ERROR_INVALID_DATA_CHARACTER:
499 *errmsg = _("] is an invalid data character in JavaScript compatibility mode");
501 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME:
502 *errmsg = _("different names for subpatterns of the same number are not allowed");
504 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
505 *errmsg = _("(*MARK) must have an argument");
507 case G_REGEX_ERROR_INVALID_CONTROL_CHAR:
508 *errmsg = _( "\\c must be followed by an ASCII character");
510 case G_REGEX_ERROR_MISSING_NAME:
511 *errmsg = _("\\k is not followed by a braced, angle-bracketed, or quoted name");
513 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS:
514 *errmsg = _("\\N is not supported in a class");
516 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES:
517 *errmsg = _("too many forward references");
519 case G_REGEX_ERROR_NAME_TOO_LONG:
520 *errmsg = _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
522 case G_REGEX_ERROR_CHARACTER_VALUE_TOO_LARGE:
523 *errmsg = _("character value in \\u.... sequence is too large");
526 case 116: /* erroffset passed as NULL */
527 /* This should not happen as we never pass a NULL erroffset */
528 g_warning ("erroffset passed as NULL");
529 *errcode = G_REGEX_ERROR_COMPILE;
531 case 117: /* unknown option bit(s) set */
532 /* This should not happen as we check options before passing them
533 * to pcre_compile2() */
534 g_warning ("unknown option bit(s) set");
535 *errcode = G_REGEX_ERROR_COMPILE;
537 case 132: /* this version of PCRE is compiled without UTF support */
538 case 144: /* invalid UTF-8 string */
539 case 145: /* support for \\P, \\p, and \\X has not been compiled */
540 case 167: /* this version of PCRE is not compiled with Unicode property support */
541 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
542 case 174: /* invalid UTF-16 string */
543 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
544 * and we do not check if strings are valid */
545 case 170: /* internal error: unknown opcode in find_fixedlength() */
546 *errcode = G_REGEX_ERROR_INTERNAL;
550 *errcode = G_REGEX_ERROR_COMPILE;
557 match_info_new (const GRegex *regex,
564 GMatchInfo *match_info;
567 string_len = strlen (string);
569 match_info = g_new0 (GMatchInfo, 1);
570 match_info->ref_count = 1;
571 match_info->regex = g_regex_ref ((GRegex *)regex);
572 match_info->string = string;
573 match_info->string_len = string_len;
574 match_info->matches = PCRE_ERROR_NOMATCH;
575 match_info->pos = start_position;
576 match_info->match_opts = match_options;
580 /* These values should be enough for most cases, if they are not
581 * enough g_regex_match_all_full() will expand them. */
582 match_info->n_offsets = 24;
583 match_info->n_workspace = 100;
584 match_info->workspace = g_new (gint, match_info->n_workspace);
589 pcre_fullinfo (regex->pcre_re, regex->extra,
590 PCRE_INFO_CAPTURECOUNT, &capture_count);
591 match_info->n_offsets = (capture_count + 1) * 3;
594 match_info->offsets = g_new0 (gint, match_info->n_offsets);
595 /* Set an invalid position for the previous match. */
596 match_info->offsets[0] = -1;
597 match_info->offsets[1] = -1;
603 * g_match_info_get_regex:
604 * @match_info: a #GMatchInfo
606 * Returns #GRegex object used in @match_info. It belongs to Glib
607 * and must not be freed. Use g_regex_ref() if you need to keep it
608 * after you free @match_info object.
610 * Returns: #GRegex object used in @match_info
615 g_match_info_get_regex (const GMatchInfo *match_info)
617 g_return_val_if_fail (match_info != NULL, NULL);
618 return match_info->regex;
622 * g_match_info_get_string:
623 * @match_info: a #GMatchInfo
625 * Returns the string searched with @match_info. This is the
626 * string passed to g_regex_match() or g_regex_replace() so
627 * you may not free it before calling this function.
629 * Returns: the string searched with @match_info
634 g_match_info_get_string (const GMatchInfo *match_info)
636 g_return_val_if_fail (match_info != NULL, NULL);
637 return match_info->string;
642 * @match_info: a #GMatchInfo
644 * Increases reference count of @match_info by 1.
646 * Returns: @match_info
651 g_match_info_ref (GMatchInfo *match_info)
653 g_return_val_if_fail (match_info != NULL, NULL);
654 g_atomic_int_inc (&match_info->ref_count);
659 * g_match_info_unref:
660 * @match_info: a #GMatchInfo
662 * Decreases reference count of @match_info by 1. When reference count drops
663 * to zero, it frees all the memory associated with the match_info structure.
668 g_match_info_unref (GMatchInfo *match_info)
670 if (g_atomic_int_dec_and_test (&match_info->ref_count))
672 g_regex_unref (match_info->regex);
673 g_free (match_info->offsets);
674 g_free (match_info->workspace);
681 * @match_info: (allow-none): a #GMatchInfo, or %NULL
683 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
689 g_match_info_free (GMatchInfo *match_info)
691 if (match_info == NULL)
694 g_match_info_unref (match_info);
699 * @match_info: a #GMatchInfo structure
700 * @error: location to store the error occurring, or %NULL to ignore errors
702 * Scans for the next match using the same parameters of the previous
703 * call to g_regex_match_full() or g_regex_match() that returned
706 * The match is done on the string passed to the match function, so you
707 * cannot free it before calling this function.
709 * Returns: %TRUE is the string matched, %FALSE otherwise
714 g_match_info_next (GMatchInfo *match_info,
717 gint prev_match_start;
720 g_return_val_if_fail (match_info != NULL, FALSE);
721 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
722 g_return_val_if_fail (match_info->pos >= 0, FALSE);
724 prev_match_start = match_info->offsets[0];
725 prev_match_end = match_info->offsets[1];
727 if (match_info->pos > match_info->string_len)
729 /* we have reached the end of the string */
730 match_info->pos = -1;
731 match_info->matches = PCRE_ERROR_NOMATCH;
735 match_info->matches = pcre_exec (match_info->regex->pcre_re,
736 match_info->regex->extra,
738 match_info->string_len,
740 match_info->regex->match_opts | match_info->match_opts,
742 match_info->n_offsets);
743 if (IS_PCRE_ERROR (match_info->matches))
745 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
746 _("Error while matching regular expression %s: %s"),
747 match_info->regex->pattern, match_error (match_info->matches));
751 /* avoid infinite loops if the pattern is an empty string or something
753 if (match_info->pos == match_info->offsets[1])
755 if (match_info->pos > match_info->string_len)
757 /* we have reached the end of the string */
758 match_info->pos = -1;
759 match_info->matches = PCRE_ERROR_NOMATCH;
763 match_info->pos = NEXT_CHAR (match_info->regex,
764 &match_info->string[match_info->pos]) -
769 match_info->pos = match_info->offsets[1];
772 /* it's possible to get two identical matches when we are matching
773 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
774 * the string is "RegExTest" we have:
775 * - search at position 0: match from 0 to 0
776 * - search at position 1: match from 3 to 3
777 * - search at position 3: match from 3 to 3 (duplicate)
778 * - search at position 4: match from 5 to 5
779 * - search at position 5: match from 5 to 5 (duplicate)
780 * - search at position 6: no match -> stop
781 * so we have to ignore the duplicates.
782 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
783 if (match_info->matches >= 0 &&
784 prev_match_start == match_info->offsets[0] &&
785 prev_match_end == match_info->offsets[1])
787 /* ignore this match and search the next one */
788 return g_match_info_next (match_info, error);
791 return match_info->matches >= 0;
795 * g_match_info_matches:
796 * @match_info: a #GMatchInfo structure
798 * Returns whether the previous match operation succeeded.
800 * Returns: %TRUE if the previous match operation succeeded,
806 g_match_info_matches (const GMatchInfo *match_info)
808 g_return_val_if_fail (match_info != NULL, FALSE);
810 return match_info->matches >= 0;
814 * g_match_info_get_match_count:
815 * @match_info: a #GMatchInfo structure
817 * Retrieves the number of matched substrings (including substring 0,
818 * that is the whole matched text), so 1 is returned if the pattern
819 * has no substrings in it and 0 is returned if the match failed.
821 * If the last match was obtained using the DFA algorithm, that is
822 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
823 * count is not that of the number of capturing parentheses but that of
824 * the number of matched substrings.
826 * Returns: Number of matched substrings, or -1 if an error occurred
831 g_match_info_get_match_count (const GMatchInfo *match_info)
833 g_return_val_if_fail (match_info, -1);
835 if (match_info->matches == PCRE_ERROR_NOMATCH)
838 else if (match_info->matches < PCRE_ERROR_NOMATCH)
843 return match_info->matches;
847 * g_match_info_is_partial_match:
848 * @match_info: a #GMatchInfo structure
850 * Usually if the string passed to g_regex_match*() matches as far as
851 * it goes, but is too short to match the entire pattern, %FALSE is
852 * returned. There are circumstances where it might be helpful to
853 * distinguish this case from other cases in which there is no match.
855 * Consider, for example, an application where a human is required to
856 * type in data for a field with specific formatting requirements. An
857 * example might be a date in the form ddmmmyy, defined by the pattern
858 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
859 * If the application sees the user’s keystrokes one by one, and can
860 * check that what has been typed so far is potentially valid, it is
861 * able to raise an error as soon as a mistake is made.
863 * GRegex supports the concept of partial matching by means of the
864 * #G_REGEX_MATCH_PARTIAL_SOFT and #G_REGEX_MATCH_PARTIAL_HARD flags.
865 * When they are used, the return code for
866 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
867 * for a complete match, %FALSE otherwise. But, when these functions
868 * return %FALSE, you can check if the match was partial calling
869 * g_match_info_is_partial_match().
871 * The difference between #G_REGEX_MATCH_PARTIAL_SOFT and
872 * #G_REGEX_MATCH_PARTIAL_HARD is that when a partial match is encountered
873 * with #G_REGEX_MATCH_PARTIAL_SOFT, matching continues to search for a
874 * possible complete match, while with #G_REGEX_MATCH_PARTIAL_HARD matching
875 * stops at the partial match.
876 * When both #G_REGEX_MATCH_PARTIAL_SOFT and #G_REGEX_MATCH_PARTIAL_HARD
877 * are set, the latter takes precedence.
879 * There were formerly some restrictions on the pattern for partial matching.
880 * The restrictions no longer apply.
882 * See pcrepartial(3) for more information on partial matching.
884 * Returns: %TRUE if the match was partial, %FALSE otherwise
889 g_match_info_is_partial_match (const GMatchInfo *match_info)
891 g_return_val_if_fail (match_info != NULL, FALSE);
893 return match_info->matches == PCRE_ERROR_PARTIAL;
897 * g_match_info_expand_references:
898 * @match_info: (allow-none): a #GMatchInfo or %NULL
899 * @string_to_expand: the string to expand
900 * @error: location to store the error occurring, or %NULL to ignore errors
902 * Returns a new string containing the text in @string_to_expand with
903 * references and escape sequences expanded. References refer to the last
904 * match done with @string against @regex and have the same syntax used by
907 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
908 * passed to g_regex_new().
910 * The backreferences are extracted from the string passed to the match
911 * function, so you cannot call this function after freeing the string.
913 * @match_info may be %NULL in which case @string_to_expand must not
914 * contain references. For instance "foo\n" does not refer to an actual
915 * pattern and '\n' merely will be replaced with \n character,
916 * while to expand "\0" (whole match) one needs the result of a match.
917 * Use g_regex_check_replacement() to find out whether @string_to_expand
918 * contains references.
920 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
925 g_match_info_expand_references (const GMatchInfo *match_info,
926 const gchar *string_to_expand,
931 GError *tmp_error = NULL;
933 g_return_val_if_fail (string_to_expand != NULL, NULL);
934 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
936 list = split_replacement (string_to_expand, &tmp_error);
937 if (tmp_error != NULL)
939 g_propagate_error (error, tmp_error);
943 if (!match_info && interpolation_list_needs_match (list))
945 g_critical ("String '%s' contains references to the match, can't "
946 "expand references without GMatchInfo object",
951 result = g_string_sized_new (strlen (string_to_expand));
952 interpolate_replacement (match_info, result, list);
954 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
956 return g_string_free (result, FALSE);
960 * g_match_info_fetch:
961 * @match_info: #GMatchInfo structure
962 * @match_num: number of the sub expression
964 * Retrieves the text matching the @match_num'th capturing
965 * parentheses. 0 is the full text of the match, 1 is the first paren
966 * set, 2 the second, and so on.
968 * If @match_num is a valid sub pattern but it didn't match anything
969 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
970 * string is returned.
972 * If the match was obtained using the DFA algorithm, that is using
973 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
974 * string is not that of a set of parentheses but that of a matched
975 * substring. Substrings are matched in reverse order of length, so
976 * 0 is the longest match.
978 * The string is fetched from the string passed to the match function,
979 * so you cannot call this function after freeing the string.
981 * Returns: (allow-none): The matched substring, or %NULL if an error
982 * occurred. You have to free the string yourself
987 g_match_info_fetch (const GMatchInfo *match_info,
990 /* we cannot use pcre_get_substring() because it allocates the
991 * string using pcre_malloc(). */
995 g_return_val_if_fail (match_info != NULL, NULL);
996 g_return_val_if_fail (match_num >= 0, NULL);
998 /* match_num does not exist or it didn't matched, i.e. matching "b"
999 * against "(a)?b" then group 0 is empty. */
1000 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
1002 else if (start == -1)
1003 match = g_strdup ("");
1005 match = g_strndup (&match_info->string[start], end - start);
1011 * g_match_info_fetch_pos:
1012 * @match_info: #GMatchInfo structure
1013 * @match_num: number of the sub expression
1014 * @start_pos: (out) (allow-none): pointer to location where to store
1015 * the start position, or %NULL
1016 * @end_pos: (out) (allow-none): pointer to location where to store
1017 * the end position, or %NULL
1019 * Retrieves the position in bytes of the @match_num'th capturing
1020 * parentheses. 0 is the full text of the match, 1 is the first
1021 * paren set, 2 the second, and so on.
1023 * If @match_num is a valid sub pattern but it didn't match anything
1024 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
1025 * and @end_pos are set to -1 and %TRUE is returned.
1027 * If the match was obtained using the DFA algorithm, that is using
1028 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1029 * position is not that of a set of parentheses but that of a matched
1030 * substring. Substrings are matched in reverse order of length, so
1031 * 0 is the longest match.
1033 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
1034 * the position cannot be fetched, @start_pos and @end_pos are left
1040 g_match_info_fetch_pos (const GMatchInfo *match_info,
1045 g_return_val_if_fail (match_info != NULL, FALSE);
1046 g_return_val_if_fail (match_num >= 0, FALSE);
1048 /* make sure the sub expression number they're requesting is less than
1049 * the total number of sub expressions that were matched. */
1050 if (match_num >= match_info->matches)
1053 if (start_pos != NULL)
1054 *start_pos = match_info->offsets[2 * match_num];
1056 if (end_pos != NULL)
1057 *end_pos = match_info->offsets[2 * match_num + 1];
1063 * Returns number of first matched subpattern with name @name.
1064 * There may be more than one in case when DUPNAMES is used,
1065 * and not all subpatterns with that name match;
1066 * pcre_get_stringnumber() does not work in that case.
1069 get_matched_substring_number (const GMatchInfo *match_info,
1073 gchar *first, *last;
1076 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
1077 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
1079 /* This code is copied from pcre_get.c: get_first_set() */
1080 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
1088 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
1090 gint n = (entry[0] << 8) + entry[1];
1091 if (match_info->offsets[n*2] >= 0)
1095 return (first[0] << 8) + first[1];
1099 * g_match_info_fetch_named:
1100 * @match_info: #GMatchInfo structure
1101 * @name: name of the subexpression
1103 * Retrieves the text matching the capturing parentheses named @name.
1105 * If @name is a valid sub pattern name but it didn't match anything
1106 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1107 * then an empty string is returned.
1109 * The string is fetched from the string passed to the match function,
1110 * so you cannot call this function after freeing the string.
1112 * Returns: (allow-none): The matched substring, or %NULL if an error
1113 * occurred. You have to free the string yourself
1118 g_match_info_fetch_named (const GMatchInfo *match_info,
1121 /* we cannot use pcre_get_named_substring() because it allocates the
1122 * string using pcre_malloc(). */
1125 g_return_val_if_fail (match_info != NULL, NULL);
1126 g_return_val_if_fail (name != NULL, NULL);
1128 num = get_matched_substring_number (match_info, name);
1132 return g_match_info_fetch (match_info, num);
1136 * g_match_info_fetch_named_pos:
1137 * @match_info: #GMatchInfo structure
1138 * @name: name of the subexpression
1139 * @start_pos: (out) (allow-none): pointer to location where to store
1140 * the start position, or %NULL
1141 * @end_pos: (out) (allow-none): pointer to location where to store
1142 * the end position, or %NULL
1144 * Retrieves the position in bytes of the capturing parentheses named @name.
1146 * If @name is a valid sub pattern name but it didn't match anything
1147 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1148 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1150 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1151 * If the position cannot be fetched, @start_pos and @end_pos
1152 * are left unchanged.
1157 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
1164 g_return_val_if_fail (match_info != NULL, FALSE);
1165 g_return_val_if_fail (name != NULL, FALSE);
1167 num = get_matched_substring_number (match_info, name);
1171 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
1175 * g_match_info_fetch_all:
1176 * @match_info: a #GMatchInfo structure
1178 * Bundles up pointers to each of the matching substrings from a match
1179 * and stores them in an array of gchar pointers. The first element in
1180 * the returned array is the match number 0, i.e. the entire matched
1183 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1184 * "b" against "(a)?b") then an empty string is inserted.
1186 * If the last match was obtained using the DFA algorithm, that is using
1187 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1188 * strings are not that matched by sets of parentheses but that of the
1189 * matched substring. Substrings are matched in reverse order of length,
1190 * so the first one is the longest match.
1192 * The strings are fetched from the string passed to the match function,
1193 * so you cannot call this function after freeing the string.
1195 * Returns: (transfer full): a %NULL-terminated array of gchar *
1196 * pointers. It must be freed using g_strfreev(). If the previous
1197 * match failed %NULL is returned
1202 g_match_info_fetch_all (const GMatchInfo *match_info)
1204 /* we cannot use pcre_get_substring_list() because the returned value
1205 * isn't suitable for g_strfreev(). */
1209 g_return_val_if_fail (match_info != NULL, NULL);
1211 if (match_info->matches < 0)
1214 result = g_new (gchar *, match_info->matches + 1);
1215 for (i = 0; i < match_info->matches; i++)
1216 result[i] = g_match_info_fetch (match_info, i);
1225 G_DEFINE_QUARK (g-regex-error-quark, g_regex_error)
1231 * Increases reference count of @regex by 1.
1238 g_regex_ref (GRegex *regex)
1240 g_return_val_if_fail (regex != NULL, NULL);
1241 g_atomic_int_inc (®ex->ref_count);
1249 * Decreases reference count of @regex by 1. When reference count drops
1250 * to zero, it frees all the memory associated with the regex structure.
1255 g_regex_unref (GRegex *regex)
1257 g_return_if_fail (regex != NULL);
1259 if (g_atomic_int_dec_and_test (®ex->ref_count))
1261 g_free (regex->pattern);
1262 if (regex->pcre_re != NULL)
1263 pcre_free (regex->pcre_re);
1264 if (regex->extra != NULL)
1265 pcre_free (regex->extra);
1272 * @pattern: the regular expression
1273 * @compile_options: compile options for the regular expression, or 0
1274 * @match_options: match options for the regular expression, or 0
1275 * @error: return location for a #GError
1277 * Compiles the regular expression to an internal form, and does
1278 * the initial setup of the #GRegex structure.
1280 * Returns: a #GRegex structure. Call g_regex_unref() when you
1286 g_regex_new (const gchar *pattern,
1287 GRegexCompileFlags compile_options,
1288 GRegexMatchFlags match_options,
1293 const gchar *errmsg;
1296 gboolean optimize = FALSE;
1297 static volatile gsize initialised = 0;
1298 unsigned long int pcre_compile_options;
1299 GRegexCompileFlags nonpcre_compile_options;
1301 g_return_val_if_fail (pattern != NULL, NULL);
1302 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1303 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1304 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1306 if (g_once_init_enter (&initialised))
1308 int supports_utf8, supports_ucp;
1310 pcre_config (PCRE_CONFIG_UTF8, &supports_utf8);
1312 g_critical (_("PCRE library is compiled without UTF8 support"));
1314 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &supports_ucp);
1316 g_critical (_("PCRE library is compiled without UTF8 properties support"));
1318 g_once_init_leave (&initialised, supports_utf8 && supports_ucp ? 1 : 2);
1321 if (G_UNLIKELY (initialised != 1))
1323 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE,
1324 _("PCRE library is compiled with incompatible options"));
1328 nonpcre_compile_options = compile_options & G_REGEX_COMPILE_NONPCRE_MASK;
1330 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1331 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1332 if (compile_options & G_REGEX_OPTIMIZE)
1335 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1336 * instead uses UTF-8 only if required with PCRE_UTF8. */
1337 if (compile_options & G_REGEX_RAW)
1340 compile_options &= ~G_REGEX_RAW;
1345 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1346 match_options |= PCRE_NO_UTF8_CHECK;
1349 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1350 * not for the system one. */
1351 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1352 !(compile_options & G_REGEX_NEWLINE_LF))
1354 compile_options |= PCRE_NEWLINE_ANY;
1357 compile_options |= PCRE_UCP;
1359 /* PCRE_BSR_UNICODE is the default for the internal PCRE but
1360 * possibly not for the system one.
1362 if (~compile_options & G_REGEX_BSR_ANYCRLF)
1363 compile_options |= PCRE_BSR_UNICODE;
1365 /* compile the pattern */
1366 re = pcre_compile2 (pattern, compile_options, &errcode,
1367 &errmsg, &erroffset, NULL);
1369 /* if the compilation failed, set the error member and return
1375 /* Translate the PCRE error code to GRegexError and use a translated
1376 * error message if possible */
1377 translate_compile_error (&errcode, &errmsg);
1379 /* PCRE uses byte offsets but we want to show character offsets */
1380 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1382 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1383 _("Error while compiling regular "
1384 "expression %s at char %d: %s"),
1385 pattern, erroffset, errmsg);
1386 g_propagate_error (error, tmp_error);
1391 /* For options set at the beginning of the pattern, pcre puts them into
1392 * compile options, e.g. "(?i)foo" will make the pcre structure store
1393 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1394 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1395 compile_options = pcre_compile_options & G_REGEX_COMPILE_PCRE_MASK;
1397 /* Don't leak PCRE_NEWLINE_ANY, which is part of PCRE_NEWLINE_ANYCRLF */
1398 if ((pcre_compile_options & PCRE_NEWLINE_ANYCRLF) != PCRE_NEWLINE_ANYCRLF)
1399 compile_options &= ~PCRE_NEWLINE_ANY;
1401 compile_options |= nonpcre_compile_options;
1403 if (!(compile_options & G_REGEX_DUPNAMES))
1405 gboolean jchanged = FALSE;
1406 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1408 compile_options |= G_REGEX_DUPNAMES;
1411 regex = g_new0 (GRegex, 1);
1412 regex->ref_count = 1;
1413 regex->pattern = g_strdup (pattern);
1414 regex->pcre_re = re;
1415 regex->compile_opts = compile_options;
1416 regex->match_opts = match_options;
1420 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1423 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1424 G_REGEX_ERROR_OPTIMIZE,
1425 _("Error while optimizing "
1426 "regular expression %s: %s"),
1429 g_propagate_error (error, tmp_error);
1431 g_regex_unref (regex);
1440 * g_regex_get_pattern:
1441 * @regex: a #GRegex structure
1443 * Gets the pattern string associated with @regex, i.e. a copy of
1444 * the string passed to g_regex_new().
1446 * Returns: the pattern of @regex
1451 g_regex_get_pattern (const GRegex *regex)
1453 g_return_val_if_fail (regex != NULL, NULL);
1455 return regex->pattern;
1459 * g_regex_get_max_backref:
1462 * Returns the number of the highest back reference
1463 * in the pattern, or 0 if the pattern does not contain
1466 * Returns: the number of the highest back reference
1471 g_regex_get_max_backref (const GRegex *regex)
1475 pcre_fullinfo (regex->pcre_re, regex->extra,
1476 PCRE_INFO_BACKREFMAX, &value);
1482 * g_regex_get_capture_count:
1485 * Returns the number of capturing subpatterns in the pattern.
1487 * Returns: the number of capturing subpatterns
1492 g_regex_get_capture_count (const GRegex *regex)
1496 pcre_fullinfo (regex->pcre_re, regex->extra,
1497 PCRE_INFO_CAPTURECOUNT, &value);
1503 * g_regex_get_has_cr_or_lf:
1504 * @regex: a #GRegex structure
1506 * Checks whether the pattern contains explicit CR or LF references.
1508 * Returns: %TRUE if the pattern contains explicit CR or LF references
1513 g_regex_get_has_cr_or_lf (const GRegex *regex)
1517 pcre_fullinfo (regex->pcre_re, regex->extra,
1518 PCRE_INFO_HASCRORLF, &value);
1524 * g_regex_get_max_lookbehind:
1525 * @regex: a #GRegex structure
1527 * Gets the number of characters in the longest lookbehind assertion in the
1528 * pattern. This information is useful when doing multi-segment matching using
1529 * the partial matching facilities.
1531 * Returns: the number of characters in the longest lookbehind assertion.
1536 g_regex_get_max_lookbehind (const GRegex *regex)
1538 gint max_lookbehind;
1540 pcre_fullinfo (regex->pcre_re, regex->extra,
1541 PCRE_INFO_MAXLOOKBEHIND, &max_lookbehind);
1543 return max_lookbehind;
1547 * g_regex_get_compile_flags:
1550 * Returns the compile options that @regex was created with.
1552 * Returns: flags from #GRegexCompileFlags
1557 g_regex_get_compile_flags (const GRegex *regex)
1559 g_return_val_if_fail (regex != NULL, 0);
1561 return regex->compile_opts;
1565 * g_regex_get_match_flags:
1568 * Returns the match options that @regex was created with.
1570 * Returns: flags from #GRegexMatchFlags
1575 g_regex_get_match_flags (const GRegex *regex)
1577 g_return_val_if_fail (regex != NULL, 0);
1579 return regex->match_opts & G_REGEX_MATCH_MASK;
1583 * g_regex_match_simple:
1584 * @pattern: the regular expression
1585 * @string: the string to scan for matches
1586 * @compile_options: compile options for the regular expression, or 0
1587 * @match_options: match options, or 0
1589 * Scans for a match in @string for @pattern.
1591 * This function is equivalent to g_regex_match() but it does not
1592 * require to compile the pattern with g_regex_new(), avoiding some
1593 * lines of code when you need just to do a match without extracting
1594 * substrings, capture counts, and so on.
1596 * If this function is to be called on the same @pattern more than
1597 * once, it's more efficient to compile the pattern once with
1598 * g_regex_new() and then use g_regex_match().
1600 * Returns: %TRUE if the string matched, %FALSE otherwise
1605 g_regex_match_simple (const gchar *pattern,
1606 const gchar *string,
1607 GRegexCompileFlags compile_options,
1608 GRegexMatchFlags match_options)
1613 regex = g_regex_new (pattern, compile_options, 0, NULL);
1616 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1617 g_regex_unref (regex);
1623 * @regex: a #GRegex structure from g_regex_new()
1624 * @string: the string to scan for matches
1625 * @match_options: match options
1626 * @match_info: (out) (allow-none): pointer to location where to store
1627 * the #GMatchInfo, or %NULL if you do not need it
1629 * Scans for a match in string for the pattern in @regex.
1630 * The @match_options are combined with the match options specified
1631 * when the @regex structure was created, letting you have more
1632 * flexibility in reusing #GRegex structures.
1634 * A #GMatchInfo structure, used to get information on the match,
1635 * is stored in @match_info if not %NULL. Note that if @match_info
1636 * is not %NULL then it is created even if the function returns %FALSE,
1637 * i.e. you must free it regardless if regular expression actually matched.
1639 * To retrieve all the non-overlapping matches of the pattern in
1640 * string you can use g_match_info_next().
1642 * |[<!-- language="C" -->
1644 * print_uppercase_words (const gchar *string)
1646 * /* Print all uppercase-only words. */
1648 * GMatchInfo *match_info;
1650 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1651 * g_regex_match (regex, string, 0, &match_info);
1652 * while (g_match_info_matches (match_info))
1654 * gchar *word = g_match_info_fetch (match_info, 0);
1655 * g_print ("Found: %s\n", word);
1657 * g_match_info_next (match_info, NULL);
1659 * g_match_info_free (match_info);
1660 * g_regex_unref (regex);
1664 * @string is not copied and is used in #GMatchInfo internally. If
1665 * you use any #GMatchInfo method (except g_match_info_free()) after
1666 * freeing or modifying @string then the behaviour is undefined.
1668 * Returns: %TRUE is the string matched, %FALSE otherwise
1673 g_regex_match (const GRegex *regex,
1674 const gchar *string,
1675 GRegexMatchFlags match_options,
1676 GMatchInfo **match_info)
1678 return g_regex_match_full (regex, string, -1, 0, match_options,
1683 * g_regex_match_full:
1684 * @regex: a #GRegex structure from g_regex_new()
1685 * @string: (array length=string_len): the string to scan for matches
1686 * @string_len: the length of @string, or -1 if @string is nul-terminated
1687 * @start_position: starting index of the string to match
1688 * @match_options: match options
1689 * @match_info: (out) (allow-none): pointer to location where to store
1690 * the #GMatchInfo, or %NULL if you do not need it
1691 * @error: location to store the error occurring, or %NULL to ignore errors
1693 * Scans for a match in string for the pattern in @regex.
1694 * The @match_options are combined with the match options specified
1695 * when the @regex structure was created, letting you have more
1696 * flexibility in reusing #GRegex structures.
1698 * Setting @start_position differs from just passing over a shortened
1699 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1700 * that begins with any kind of lookbehind assertion, such as "\b".
1702 * A #GMatchInfo structure, used to get information on the match, is
1703 * stored in @match_info if not %NULL. Note that if @match_info is
1704 * not %NULL then it is created even if the function returns %FALSE,
1705 * i.e. you must free it regardless if regular expression actually
1708 * @string is not copied and is used in #GMatchInfo internally. If
1709 * you use any #GMatchInfo method (except g_match_info_free()) after
1710 * freeing or modifying @string then the behaviour is undefined.
1712 * To retrieve all the non-overlapping matches of the pattern in
1713 * string you can use g_match_info_next().
1715 * |[<!-- language="C" -->
1717 * print_uppercase_words (const gchar *string)
1719 * /* Print all uppercase-only words. */
1721 * GMatchInfo *match_info;
1722 * GError *error = NULL;
1724 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1725 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1726 * while (g_match_info_matches (match_info))
1728 * gchar *word = g_match_info_fetch (match_info, 0);
1729 * g_print ("Found: %s\n", word);
1731 * g_match_info_next (match_info, &error);
1733 * g_match_info_free (match_info);
1734 * g_regex_unref (regex);
1735 * if (error != NULL)
1737 * g_printerr ("Error while matching: %s\n", error->message);
1738 * g_error_free (error);
1743 * Returns: %TRUE is the string matched, %FALSE otherwise
1748 g_regex_match_full (const GRegex *regex,
1749 const gchar *string,
1751 gint start_position,
1752 GRegexMatchFlags match_options,
1753 GMatchInfo **match_info,
1759 g_return_val_if_fail (regex != NULL, FALSE);
1760 g_return_val_if_fail (string != NULL, FALSE);
1761 g_return_val_if_fail (start_position >= 0, FALSE);
1762 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1763 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1765 info = match_info_new (regex, string, string_len, start_position,
1766 match_options, FALSE);
1767 match_ok = g_match_info_next (info, error);
1768 if (match_info != NULL)
1771 g_match_info_free (info);
1777 * g_regex_match_all:
1778 * @regex: a #GRegex structure from g_regex_new()
1779 * @string: the string to scan for matches
1780 * @match_options: match options
1781 * @match_info: (out) (allow-none): pointer to location where to store
1782 * the #GMatchInfo, or %NULL if you do not need it
1784 * Using the standard algorithm for regular expression matching only
1785 * the longest match in the string is retrieved. This function uses
1786 * a different algorithm so it can retrieve all the possible matches.
1787 * For more documentation see g_regex_match_all_full().
1789 * A #GMatchInfo structure, used to get information on the match, is
1790 * stored in @match_info if not %NULL. Note that if @match_info is
1791 * not %NULL then it is created even if the function returns %FALSE,
1792 * i.e. you must free it regardless if regular expression actually
1795 * @string is not copied and is used in #GMatchInfo internally. If
1796 * you use any #GMatchInfo method (except g_match_info_free()) after
1797 * freeing or modifying @string then the behaviour is undefined.
1799 * Returns: %TRUE is the string matched, %FALSE otherwise
1804 g_regex_match_all (const GRegex *regex,
1805 const gchar *string,
1806 GRegexMatchFlags match_options,
1807 GMatchInfo **match_info)
1809 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1814 * g_regex_match_all_full:
1815 * @regex: a #GRegex structure from g_regex_new()
1816 * @string: (array length=string_len): the string to scan for matches
1817 * @string_len: the length of @string, or -1 if @string is nul-terminated
1818 * @start_position: starting index of the string to match
1819 * @match_options: match options
1820 * @match_info: (out) (allow-none): pointer to location where to store
1821 * the #GMatchInfo, or %NULL if you do not need it
1822 * @error: location to store the error occurring, or %NULL to ignore errors
1824 * Using the standard algorithm for regular expression matching only
1825 * the longest match in the string is retrieved, it is not possible
1826 * to obtain all the available matches. For instance matching
1827 * "<a> <b> <c>" against the pattern "<.*>"
1828 * you get "<a> <b> <c>".
1830 * This function uses a different algorithm (called DFA, i.e. deterministic
1831 * finite automaton), so it can retrieve all the possible matches, all
1832 * starting at the same point in the string. For instance matching
1833 * "<a> <b> <c>" against the pattern "<.*>;"
1834 * you would obtain three matches: "<a> <b> <c>",
1835 * "<a> <b>" and "<a>".
1837 * The number of matched strings is retrieved using
1838 * g_match_info_get_match_count(). To obtain the matched strings and
1839 * their position you can use, respectively, g_match_info_fetch() and
1840 * g_match_info_fetch_pos(). Note that the strings are returned in
1841 * reverse order of length; that is, the longest matching string is
1844 * Note that the DFA algorithm is slower than the standard one and it
1845 * is not able to capture substrings, so backreferences do not work.
1847 * Setting @start_position differs from just passing over a shortened
1848 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1849 * that begins with any kind of lookbehind assertion, such as "\b".
1851 * A #GMatchInfo structure, used to get information on the match, is
1852 * stored in @match_info if not %NULL. Note that if @match_info is
1853 * not %NULL then it is created even if the function returns %FALSE,
1854 * i.e. you must free it regardless if regular expression actually
1857 * @string is not copied and is used in #GMatchInfo internally. If
1858 * you use any #GMatchInfo method (except g_match_info_free()) after
1859 * freeing or modifying @string then the behaviour is undefined.
1861 * Returns: %TRUE is the string matched, %FALSE otherwise
1866 g_regex_match_all_full (const GRegex *regex,
1867 const gchar *string,
1869 gint start_position,
1870 GRegexMatchFlags match_options,
1871 GMatchInfo **match_info,
1877 g_return_val_if_fail (regex != NULL, FALSE);
1878 g_return_val_if_fail (string != NULL, FALSE);
1879 g_return_val_if_fail (start_position >= 0, FALSE);
1880 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1881 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1883 info = match_info_new (regex, string, string_len, start_position,
1884 match_options, TRUE);
1890 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1891 info->string, info->string_len,
1893 regex->match_opts | match_options,
1894 info->offsets, info->n_offsets,
1895 info->workspace, info->n_workspace);
1896 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1898 /* info->workspace is too small. */
1899 info->n_workspace *= 2;
1900 info->workspace = g_realloc (info->workspace,
1901 info->n_workspace * sizeof (gint));
1904 else if (info->matches == 0)
1906 /* info->offsets is too small. */
1907 info->n_offsets *= 2;
1908 info->offsets = g_realloc (info->offsets,
1909 info->n_offsets * sizeof (gint));
1912 else if (IS_PCRE_ERROR (info->matches))
1914 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1915 _("Error while matching regular expression %s: %s"),
1916 regex->pattern, match_error (info->matches));
1920 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1923 if (match_info != NULL)
1926 g_match_info_free (info);
1928 return info->matches >= 0;
1932 * g_regex_get_string_number:
1933 * @regex: #GRegex structure
1934 * @name: name of the subexpression
1936 * Retrieves the number of the subexpression named @name.
1938 * Returns: The number of the subexpression or -1 if @name
1944 g_regex_get_string_number (const GRegex *regex,
1949 g_return_val_if_fail (regex != NULL, -1);
1950 g_return_val_if_fail (name != NULL, -1);
1952 num = pcre_get_stringnumber (regex->pcre_re, name);
1953 if (num == PCRE_ERROR_NOSUBSTRING)
1960 * g_regex_split_simple:
1961 * @pattern: the regular expression
1962 * @string: the string to scan for matches
1963 * @compile_options: compile options for the regular expression, or 0
1964 * @match_options: match options, or 0
1966 * Breaks the string on the pattern, and returns an array of
1967 * the tokens. If the pattern contains capturing parentheses,
1968 * then the text for each of the substrings will also be returned.
1969 * If the pattern does not match anywhere in the string, then the
1970 * whole string is returned as the first token.
1972 * This function is equivalent to g_regex_split() but it does
1973 * not require to compile the pattern with g_regex_new(), avoiding
1974 * some lines of code when you need just to do a split without
1975 * extracting substrings, capture counts, and so on.
1977 * If this function is to be called on the same @pattern more than
1978 * once, it's more efficient to compile the pattern once with
1979 * g_regex_new() and then use g_regex_split().
1981 * As a special case, the result of splitting the empty string ""
1982 * is an empty vector, not a vector containing a single string.
1983 * The reason for this special case is that being able to represent
1984 * a empty vector is typically more useful than consistent handling
1985 * of empty elements. If you do need to represent empty elements,
1986 * you'll need to check for the empty string before calling this
1989 * A pattern that can match empty strings splits @string into
1990 * separate characters wherever it matches the empty string between
1991 * characters. For example splitting "ab c" using as a separator
1992 * "\s*", you will get "a", "b" and "c".
1994 * Returns: (transfer full): a %NULL-terminated array of strings. Free
1995 * it using g_strfreev()
2000 g_regex_split_simple (const gchar *pattern,
2001 const gchar *string,
2002 GRegexCompileFlags compile_options,
2003 GRegexMatchFlags match_options)
2008 regex = g_regex_new (pattern, compile_options, 0, NULL);
2012 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
2013 g_regex_unref (regex);
2019 * @regex: a #GRegex structure
2020 * @string: the string to split with the pattern
2021 * @match_options: match time option flags
2023 * Breaks the string on the pattern, and returns an array of the tokens.
2024 * If the pattern contains capturing parentheses, then the text for each
2025 * of the substrings will also be returned. If the pattern does not match
2026 * anywhere in the string, then the whole string is returned as the first
2029 * As a special case, the result of splitting the empty string "" is an
2030 * empty vector, not a vector containing a single string. The reason for
2031 * this special case is that being able to represent a empty vector is
2032 * typically more useful than consistent handling of empty elements. If
2033 * you do need to represent empty elements, you'll need to check for the
2034 * empty string before calling this function.
2036 * A pattern that can match empty strings splits @string into separate
2037 * characters wherever it matches the empty string between characters.
2038 * For example splitting "ab c" using as a separator "\s*", you will get
2041 * Returns: (transfer full): a %NULL-terminated gchar ** array. Free
2042 * it using g_strfreev()
2047 g_regex_split (const GRegex *regex,
2048 const gchar *string,
2049 GRegexMatchFlags match_options)
2051 return g_regex_split_full (regex, string, -1, 0,
2052 match_options, 0, NULL);
2056 * g_regex_split_full:
2057 * @regex: a #GRegex structure
2058 * @string: (array length=string_len): the string to split with the pattern
2059 * @string_len: the length of @string, or -1 if @string is nul-terminated
2060 * @start_position: starting index of the string to match
2061 * @match_options: match time option flags
2062 * @max_tokens: the maximum number of tokens to split @string into.
2063 * If this is less than 1, the string is split completely
2064 * @error: return location for a #GError
2066 * Breaks the string on the pattern, and returns an array of the tokens.
2067 * If the pattern contains capturing parentheses, then the text for each
2068 * of the substrings will also be returned. If the pattern does not match
2069 * anywhere in the string, then the whole string is returned as the first
2072 * As a special case, the result of splitting the empty string "" is an
2073 * empty vector, not a vector containing a single string. The reason for
2074 * this special case is that being able to represent a empty vector is
2075 * typically more useful than consistent handling of empty elements. If
2076 * you do need to represent empty elements, you'll need to check for the
2077 * empty string before calling this function.
2079 * A pattern that can match empty strings splits @string into separate
2080 * characters wherever it matches the empty string between characters.
2081 * For example splitting "ab c" using as a separator "\s*", you will get
2084 * Setting @start_position differs from just passing over a shortened
2085 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2086 * that begins with any kind of lookbehind assertion, such as "\b".
2088 * Returns: (transfer full): a %NULL-terminated gchar ** array. Free
2089 * it using g_strfreev()
2094 g_regex_split_full (const GRegex *regex,
2095 const gchar *string,
2097 gint start_position,
2098 GRegexMatchFlags match_options,
2102 GError *tmp_error = NULL;
2103 GMatchInfo *match_info;
2108 /* position of the last separator. */
2109 gint last_separator_end;
2110 /* was the last match 0 bytes long? */
2111 gboolean last_match_is_empty;
2112 /* the returned array of char **s */
2113 gchar **string_list;
2115 g_return_val_if_fail (regex != NULL, NULL);
2116 g_return_val_if_fail (string != NULL, NULL);
2117 g_return_val_if_fail (start_position >= 0, NULL);
2118 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2119 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2121 if (max_tokens <= 0)
2122 max_tokens = G_MAXINT;
2125 string_len = strlen (string);
2127 /* zero-length string */
2128 if (string_len - start_position == 0)
2129 return g_new0 (gchar *, 1);
2131 if (max_tokens == 1)
2133 string_list = g_new0 (gchar *, 2);
2134 string_list[0] = g_strndup (&string[start_position],
2135 string_len - start_position);
2141 last_separator_end = start_position;
2142 last_match_is_empty = FALSE;
2144 match_ok = g_regex_match_full (regex, string, string_len, start_position,
2145 match_options, &match_info, &tmp_error);
2147 while (tmp_error == NULL)
2151 last_match_is_empty =
2152 (match_info->offsets[0] == match_info->offsets[1]);
2154 /* we need to skip empty separators at the same position of the end
2155 * of another separator. e.g. the string is "a b" and the separator
2156 * is " *", so from 1 to 2 we have a match and at position 2 we have
2157 * an empty match. */
2158 if (last_separator_end != match_info->offsets[1])
2163 token = g_strndup (string + last_separator_end,
2164 match_info->offsets[0] - last_separator_end);
2165 list = g_list_prepend (list, token);
2168 /* if there were substrings, these need to be added to
2170 match_count = g_match_info_get_match_count (match_info);
2171 if (match_count > 1)
2173 for (i = 1; i < match_count; i++)
2174 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
2180 /* if there was no match, copy to end of string. */
2181 if (!last_match_is_empty)
2183 gchar *token = g_strndup (string + last_separator_end,
2184 match_info->string_len - last_separator_end);
2185 list = g_list_prepend (list, token);
2187 /* no more tokens, end the loop. */
2191 /* -1 to leave room for the last part. */
2192 if (token_count >= max_tokens - 1)
2194 /* we have reached the maximum number of tokens, so we copy
2195 * the remaining part of the string. */
2196 if (last_match_is_empty)
2198 /* the last match was empty, so we have moved one char
2199 * after the real position to avoid empty matches at the
2201 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
2203 /* the if is needed in the case we have terminated the available
2204 * tokens, but we are at the end of the string, so there are no
2205 * characters left to copy. */
2206 if (string_len > match_info->pos)
2208 gchar *token = g_strndup (string + match_info->pos,
2209 string_len - match_info->pos);
2210 list = g_list_prepend (list, token);
2216 last_separator_end = match_info->pos;
2217 if (last_match_is_empty)
2218 /* if the last match was empty, g_match_info_next() has moved
2219 * forward to avoid infinite loops, but we still need to copy that
2221 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
2223 match_ok = g_match_info_next (match_info, &tmp_error);
2225 g_match_info_free (match_info);
2226 if (tmp_error != NULL)
2228 g_propagate_error (error, tmp_error);
2229 g_list_free_full (list, g_free);
2230 match_info->pos = -1;
2234 string_list = g_new (gchar *, g_list_length (list) + 1);
2236 for (last = g_list_last (list); last; last = g_list_previous (last))
2237 string_list[i++] = last->data;
2238 string_list[i] = NULL;
2247 REPL_TYPE_CHARACTER,
2248 REPL_TYPE_SYMBOLIC_REFERENCE,
2249 REPL_TYPE_NUMERIC_REFERENCE,
2250 REPL_TYPE_CHANGE_CASE
2255 CHANGE_CASE_NONE = 1 << 0,
2256 CHANGE_CASE_UPPER = 1 << 1,
2257 CHANGE_CASE_LOWER = 1 << 2,
2258 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
2259 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
2260 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
2261 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
2262 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
2265 struct _InterpolationData
2271 ChangeCase change_case;
2275 free_interpolation_data (InterpolationData *data)
2277 g_free (data->text);
2281 static const gchar *
2282 expand_escape (const gchar *replacement,
2284 InterpolationData *data,
2289 const gchar *error_detail;
2291 GError *tmp_error = NULL;
2299 data->type = REPL_TYPE_CHARACTER;
2304 data->type = REPL_TYPE_CHARACTER;
2309 data->type = REPL_TYPE_CHARACTER;
2314 data->type = REPL_TYPE_CHARACTER;
2319 data->type = REPL_TYPE_CHARACTER;
2324 data->type = REPL_TYPE_CHARACTER;
2329 data->type = REPL_TYPE_CHARACTER;
2334 data->type = REPL_TYPE_CHARACTER;
2344 h = g_ascii_xdigit_value (*p);
2347 error_detail = _("hexadecimal digit or '}' expected");
2358 for (i = 0; i < 2; i++)
2360 h = g_ascii_xdigit_value (*p);
2363 error_detail = _("hexadecimal digit expected");
2370 data->type = REPL_TYPE_STRING;
2371 data->text = g_new0 (gchar, 8);
2372 g_unichar_to_utf8 (x, data->text);
2376 data->type = REPL_TYPE_CHANGE_CASE;
2377 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2381 data->type = REPL_TYPE_CHANGE_CASE;
2382 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2386 data->type = REPL_TYPE_CHANGE_CASE;
2387 data->change_case = CHANGE_CASE_LOWER;
2391 data->type = REPL_TYPE_CHANGE_CASE;
2392 data->change_case = CHANGE_CASE_UPPER;
2396 data->type = REPL_TYPE_CHANGE_CASE;
2397 data->change_case = CHANGE_CASE_NONE;
2403 error_detail = _("missing '<' in symbolic reference");
2412 error_detail = _("unfinished symbolic reference");
2419 error_detail = _("zero-length symbolic reference");
2422 if (g_ascii_isdigit (*q))
2427 h = g_ascii_digit_value (*q);
2430 error_detail = _("digit expected");
2439 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2446 if (!g_ascii_isalnum (*r))
2448 error_detail = _("illegal symbolic reference");
2455 data->text = g_strndup (q, p - q);
2456 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2461 /* if \0 is followed by a number is an octal number representing a
2462 * character, else it is a numeric reference. */
2463 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2466 p = g_utf8_next_char (p);
2479 for (i = 0; i < 3; i++)
2481 h = g_ascii_digit_value (*p);
2491 if (i == 2 && base == 10)
2497 if (base == 8 || i == 3)
2499 data->type = REPL_TYPE_STRING;
2500 data->text = g_new0 (gchar, 8);
2501 g_unichar_to_utf8 (x, data->text);
2505 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2510 error_detail = _("stray final '\\'");
2514 error_detail = _("unknown escape sequence");
2521 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2522 tmp_error = g_error_new (G_REGEX_ERROR,
2523 G_REGEX_ERROR_REPLACE,
2524 _("Error while parsing replacement "
2525 "text \"%s\" at char %lu: %s"),
2527 (gulong)(p - replacement),
2529 g_propagate_error (error, tmp_error);
2535 split_replacement (const gchar *replacement,
2539 InterpolationData *data;
2540 const gchar *p, *start;
2542 start = p = replacement;
2547 data = g_new0 (InterpolationData, 1);
2548 start = p = expand_escape (replacement, p, data, error);
2551 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2552 free_interpolation_data (data);
2556 list = g_list_prepend (list, data);
2561 if (*p == '\\' || *p == '\0')
2565 data = g_new0 (InterpolationData, 1);
2566 data->text = g_strndup (start, p - start);
2567 data->type = REPL_TYPE_STRING;
2568 list = g_list_prepend (list, data);
2574 return g_list_reverse (list);
2577 /* Change the case of c based on change_case. */
2578 #define CHANGE_CASE(c, change_case) \
2579 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2580 g_unichar_tolower (c) : \
2581 g_unichar_toupper (c))
2584 string_append (GString *string,
2586 ChangeCase *change_case)
2590 if (text[0] == '\0')
2593 if (*change_case == CHANGE_CASE_NONE)
2595 g_string_append (string, text);
2597 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2599 c = g_utf8_get_char (text);
2600 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2601 g_string_append (string, g_utf8_next_char (text));
2602 *change_case = CHANGE_CASE_NONE;
2606 while (*text != '\0')
2608 c = g_utf8_get_char (text);
2609 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2610 text = g_utf8_next_char (text);
2616 interpolate_replacement (const GMatchInfo *match_info,
2621 InterpolationData *idata;
2623 ChangeCase change_case = CHANGE_CASE_NONE;
2625 for (list = data; list; list = list->next)
2628 switch (idata->type)
2630 case REPL_TYPE_STRING:
2631 string_append (result, idata->text, &change_case);
2633 case REPL_TYPE_CHARACTER:
2634 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2635 if (change_case & CHANGE_CASE_SINGLE_MASK)
2636 change_case = CHANGE_CASE_NONE;
2638 case REPL_TYPE_NUMERIC_REFERENCE:
2639 match = g_match_info_fetch (match_info, idata->num);
2642 string_append (result, match, &change_case);
2646 case REPL_TYPE_SYMBOLIC_REFERENCE:
2647 match = g_match_info_fetch_named (match_info, idata->text);
2650 string_append (result, match, &change_case);
2654 case REPL_TYPE_CHANGE_CASE:
2655 change_case = idata->change_case;
2663 /* whether actual match_info is needed for replacement, i.e.
2664 * whether there are references
2667 interpolation_list_needs_match (GList *list)
2669 while (list != NULL)
2671 InterpolationData *data = list->data;
2673 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2674 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2687 * @regex: a #GRegex structure
2688 * @string: (array length=string_len): the string to perform matches against
2689 * @string_len: the length of @string, or -1 if @string is nul-terminated
2690 * @start_position: starting index of the string to match
2691 * @replacement: text to replace each match with
2692 * @match_options: options for the match
2693 * @error: location to store the error occurring, or %NULL to ignore errors
2695 * Replaces all occurrences of the pattern in @regex with the
2696 * replacement text. Backreferences of the form '\number' or
2697 * '\g<number>' in the replacement text are interpolated by the
2698 * number-th captured subexpression of the match, '\g<name>' refers
2699 * to the captured subexpression with the given name. '\0' refers
2700 * to the complete match, but '\0' followed by a number is the octal
2701 * representation of a character. To include a literal '\' in the
2702 * replacement, write '\\'.
2704 * There are also escapes that changes the case of the following text:
2706 * - \l: Convert to lower case the next character
2707 * - \u: Convert to upper case the next character
2708 * - \L: Convert to lower case till \E
2709 * - \U: Convert to upper case till \E
2710 * - \E: End case modification
2712 * If you do not need to use backreferences use g_regex_replace_literal().
2714 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2715 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2716 * you can use g_regex_replace_literal().
2718 * Setting @start_position differs from just passing over a shortened
2719 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2720 * begins with any kind of lookbehind assertion, such as "\b".
2722 * Returns: a newly allocated string containing the replacements
2727 g_regex_replace (const GRegex *regex,
2728 const gchar *string,
2730 gint start_position,
2731 const gchar *replacement,
2732 GRegexMatchFlags match_options,
2737 GError *tmp_error = NULL;
2739 g_return_val_if_fail (regex != NULL, NULL);
2740 g_return_val_if_fail (string != NULL, NULL);
2741 g_return_val_if_fail (start_position >= 0, NULL);
2742 g_return_val_if_fail (replacement != NULL, NULL);
2743 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2744 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2746 list = split_replacement (replacement, &tmp_error);
2747 if (tmp_error != NULL)
2749 g_propagate_error (error, tmp_error);
2753 result = g_regex_replace_eval (regex,
2754 string, string_len, start_position,
2756 interpolate_replacement,
2759 if (tmp_error != NULL)
2760 g_propagate_error (error, tmp_error);
2762 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2768 literal_replacement (const GMatchInfo *match_info,
2772 g_string_append (result, data);
2777 * g_regex_replace_literal:
2778 * @regex: a #GRegex structure
2779 * @string: (array length=string_len): the string to perform matches against
2780 * @string_len: the length of @string, or -1 if @string is nul-terminated
2781 * @start_position: starting index of the string to match
2782 * @replacement: text to replace each match with
2783 * @match_options: options for the match
2784 * @error: location to store the error occurring, or %NULL to ignore errors
2786 * Replaces all occurrences of the pattern in @regex with the
2787 * replacement text. @replacement is replaced literally, to
2788 * include backreferences use g_regex_replace().
2790 * Setting @start_position differs from just passing over a
2791 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2792 * case of a pattern that begins with any kind of lookbehind
2793 * assertion, such as "\b".
2795 * Returns: a newly allocated string containing the replacements
2800 g_regex_replace_literal (const GRegex *regex,
2801 const gchar *string,
2803 gint start_position,
2804 const gchar *replacement,
2805 GRegexMatchFlags match_options,
2808 g_return_val_if_fail (replacement != NULL, NULL);
2809 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2811 return g_regex_replace_eval (regex,
2812 string, string_len, start_position,
2814 literal_replacement,
2815 (gpointer)replacement,
2820 * g_regex_replace_eval:
2821 * @regex: a #GRegex structure from g_regex_new()
2822 * @string: (array length=string_len): string to perform matches against
2823 * @string_len: the length of @string, or -1 if @string is nul-terminated
2824 * @start_position: starting index of the string to match
2825 * @match_options: options for the match
2826 * @eval: a function to call for each match
2827 * @user_data: user data to pass to the function
2828 * @error: location to store the error occurring, or %NULL to ignore errors
2830 * Replaces occurrences of the pattern in regex with the output of
2831 * @eval for that occurrence.
2833 * Setting @start_position differs from just passing over a shortened
2834 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2835 * that begins with any kind of lookbehind assertion, such as "\b".
2837 * The following example uses g_regex_replace_eval() to replace multiple
2839 * |[<!-- language="C" -->
2841 * eval_cb (const GMatchInfo *info,
2848 * match = g_match_info_fetch (info, 0);
2849 * r = g_hash_table_lookup ((GHashTable *)data, match);
2850 * g_string_append (res, r);
2862 * h = g_hash_table_new (g_str_hash, g_str_equal);
2864 * g_hash_table_insert (h, "1", "ONE");
2865 * g_hash_table_insert (h, "2", "TWO");
2866 * g_hash_table_insert (h, "3", "THREE");
2867 * g_hash_table_insert (h, "4", "FOUR");
2869 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2870 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2871 * g_hash_table_destroy (h);
2876 * Returns: a newly allocated string containing the replacements
2881 g_regex_replace_eval (const GRegex *regex,
2882 const gchar *string,
2884 gint start_position,
2885 GRegexMatchFlags match_options,
2886 GRegexEvalCallback eval,
2890 GMatchInfo *match_info;
2893 gboolean done = FALSE;
2894 GError *tmp_error = NULL;
2896 g_return_val_if_fail (regex != NULL, NULL);
2897 g_return_val_if_fail (string != NULL, NULL);
2898 g_return_val_if_fail (start_position >= 0, NULL);
2899 g_return_val_if_fail (eval != NULL, NULL);
2900 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2903 string_len = strlen (string);
2905 result = g_string_sized_new (string_len);
2907 /* run down the string making matches. */
2908 g_regex_match_full (regex, string, string_len, start_position,
2909 match_options, &match_info, &tmp_error);
2910 while (!done && g_match_info_matches (match_info))
2912 g_string_append_len (result,
2914 match_info->offsets[0] - str_pos);
2915 done = (*eval) (match_info, result, user_data);
2916 str_pos = match_info->offsets[1];
2917 g_match_info_next (match_info, &tmp_error);
2919 g_match_info_free (match_info);
2920 if (tmp_error != NULL)
2922 g_propagate_error (error, tmp_error);
2923 g_string_free (result, TRUE);
2927 g_string_append_len (result, string + str_pos, string_len - str_pos);
2928 return g_string_free (result, FALSE);
2932 * g_regex_check_replacement:
2933 * @replacement: the replacement string
2934 * @has_references: (out) (allow-none): location to store information about
2935 * references in @replacement or %NULL
2936 * @error: location to store error
2938 * Checks whether @replacement is a valid replacement string
2939 * (see g_regex_replace()), i.e. that all escape sequences in
2942 * If @has_references is not %NULL then @replacement is checked
2943 * for pattern references. For instance, replacement text 'foo\n'
2944 * does not contain references and may be evaluated without information
2945 * about actual match, but '\0\1' (whole match followed by first
2946 * subpattern) requires valid #GMatchInfo object.
2948 * Returns: whether @replacement is a valid replacement string
2953 g_regex_check_replacement (const gchar *replacement,
2954 gboolean *has_references,
2960 list = split_replacement (replacement, &tmp);
2964 g_propagate_error (error, tmp);
2969 *has_references = interpolation_list_needs_match (list);
2971 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2977 * g_regex_escape_nul:
2978 * @string: the string to escape
2979 * @length: the length of @string
2981 * Escapes the nul characters in @string to "\x00". It can be used
2982 * to compile a regex with embedded nul characters.
2984 * For completeness, @length can be -1 for a nul-terminated string.
2985 * In this case the output string will be of course equal to @string.
2987 * Returns: a newly-allocated escaped string
2992 g_regex_escape_nul (const gchar *string,
2996 const gchar *p, *piece_start, *end;
2999 g_return_val_if_fail (string != NULL, NULL);
3002 return g_strdup (string);
3004 end = string + length;
3005 p = piece_start = string;
3006 escaped = g_string_sized_new (length + 1);
3014 if (p != piece_start)
3016 /* copy the previous piece. */
3017 g_string_append_len (escaped, piece_start, p - piece_start);
3019 if ((backslashes & 1) == 0)
3020 g_string_append_c (escaped, '\\');
3021 g_string_append_c (escaped, 'x');
3022 g_string_append_c (escaped, '0');
3023 g_string_append_c (escaped, '0');
3033 p = g_utf8_next_char (p);
3038 if (piece_start < end)
3039 g_string_append_len (escaped, piece_start, end - piece_start);
3041 return g_string_free (escaped, FALSE);
3045 * g_regex_escape_string:
3046 * @string: (array length=length): the string to escape
3047 * @length: the length of @string, or -1 if @string is nul-terminated
3049 * Escapes the special characters used for regular expressions
3050 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
3051 * function is useful to dynamically generate regular expressions.
3053 * @string can contain nul characters that are replaced with "\0",
3054 * in this case remember to specify the correct length of @string
3057 * Returns: a newly-allocated escaped string
3062 g_regex_escape_string (const gchar *string,
3066 const char *p, *piece_start, *end;
3068 g_return_val_if_fail (string != NULL, NULL);
3071 length = strlen (string);
3073 end = string + length;
3074 p = piece_start = string;
3075 escaped = g_string_sized_new (length + 1);
3096 if (p != piece_start)
3097 /* copy the previous piece. */
3098 g_string_append_len (escaped, piece_start, p - piece_start);
3099 g_string_append_c (escaped, '\\');
3101 g_string_append_c (escaped, '0');
3103 g_string_append_c (escaped, *p);
3107 p = g_utf8_next_char (p);
3112 if (piece_start < end)
3113 g_string_append_len (escaped, piece_start, end - piece_start);
3115 return g_string_free (escaped, FALSE);