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: <xref linkend="glib-regex-syntax"/>
47 * The <function>g_regex_*()</function> 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 * <ulink>man:pcreapi(3)<ulink> 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
109 * the excellent <ulink url="http://www.pcre.org/">PCRE</ulink> library
110 * written by Philip Hazel.
113 /* Mask of all the possible values for GRegexCompileFlags. */
114 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
115 G_REGEX_MULTILINE | \
119 G_REGEX_DOLLAR_ENDONLY | \
122 G_REGEX_NO_AUTO_CAPTURE | \
125 G_REGEX_NEWLINE_CR | \
126 G_REGEX_NEWLINE_LF | \
127 G_REGEX_NEWLINE_CRLF | \
128 G_REGEX_NEWLINE_ANYCRLF | \
129 G_REGEX_BSR_ANYCRLF | \
130 G_REGEX_JAVASCRIPT_COMPAT)
132 /* Mask of all GRegexCompileFlags values that are (not) passed trough to PCRE */
133 #define G_REGEX_COMPILE_PCRE_MASK (G_REGEX_COMPILE_MASK & ~G_REGEX_COMPILE_NONPCRE_MASK)
134 #define G_REGEX_COMPILE_NONPCRE_MASK (G_REGEX_RAW | \
137 /* Mask of all the possible values for GRegexMatchFlags. */
138 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
139 G_REGEX_MATCH_NOTBOL | \
140 G_REGEX_MATCH_NOTEOL | \
141 G_REGEX_MATCH_NOTEMPTY | \
142 G_REGEX_MATCH_PARTIAL | \
143 G_REGEX_MATCH_NEWLINE_CR | \
144 G_REGEX_MATCH_NEWLINE_LF | \
145 G_REGEX_MATCH_NEWLINE_CRLF | \
146 G_REGEX_MATCH_NEWLINE_ANY | \
147 G_REGEX_MATCH_NEWLINE_ANYCRLF | \
148 G_REGEX_MATCH_BSR_ANYCRLF | \
149 G_REGEX_MATCH_BSR_ANY | \
150 G_REGEX_MATCH_PARTIAL_SOFT | \
151 G_REGEX_MATCH_PARTIAL_HARD | \
152 G_REGEX_MATCH_NOTEMPTY_ATSTART)
154 /* we rely on these flags having the same values */
155 G_STATIC_ASSERT (G_REGEX_CASELESS == PCRE_CASELESS);
156 G_STATIC_ASSERT (G_REGEX_MULTILINE == PCRE_MULTILINE);
157 G_STATIC_ASSERT (G_REGEX_DOTALL == PCRE_DOTALL);
158 G_STATIC_ASSERT (G_REGEX_EXTENDED == PCRE_EXTENDED);
159 G_STATIC_ASSERT (G_REGEX_ANCHORED == PCRE_ANCHORED);
160 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY == PCRE_DOLLAR_ENDONLY);
161 G_STATIC_ASSERT (G_REGEX_UNGREEDY == PCRE_UNGREEDY);
162 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE == PCRE_NO_AUTO_CAPTURE);
163 G_STATIC_ASSERT (G_REGEX_DUPNAMES == PCRE_DUPNAMES);
164 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR == PCRE_NEWLINE_CR);
165 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF == PCRE_NEWLINE_LF);
166 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
167 G_STATIC_ASSERT (G_REGEX_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
168 G_STATIC_ASSERT (G_REGEX_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
169 G_STATIC_ASSERT (G_REGEX_JAVASCRIPT_COMPAT == PCRE_JAVASCRIPT_COMPAT);
171 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED == PCRE_ANCHORED);
172 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL == PCRE_NOTBOL);
173 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL == PCRE_NOTEOL);
174 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY == PCRE_NOTEMPTY);
175 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL == PCRE_PARTIAL);
176 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR == PCRE_NEWLINE_CR);
177 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF == PCRE_NEWLINE_LF);
178 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
179 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY == PCRE_NEWLINE_ANY);
180 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
181 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
182 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANY == PCRE_BSR_UNICODE);
183 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL_SOFT == PCRE_PARTIAL_SOFT);
184 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL_HARD == PCRE_PARTIAL_HARD);
185 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY_ATSTART == PCRE_NOTEMPTY_ATSTART);
187 /* These PCRE flags are unused or not exposed publically in GRegexFlags, so
188 * it should be ok to reuse them for different things.
190 G_STATIC_ASSERT (G_REGEX_OPTIMIZE == PCRE_NO_UTF8_CHECK);
191 G_STATIC_ASSERT (G_REGEX_RAW == PCRE_UTF8);
193 /* if the string is in UTF-8 use g_utf8_ functions, else use
195 #define NEXT_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
197 g_utf8_next_char (s))
198 #define PREV_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
200 g_utf8_prev_char (s))
204 volatile gint ref_count; /* the ref count */
205 GRegex *regex; /* the regex */
206 GRegexMatchFlags match_opts; /* options used at match time on the regex */
207 gint matches; /* number of matching sub patterns */
208 gint pos; /* position in the string where last match left off */
209 gint n_offsets; /* number of offsets */
210 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
211 gint *workspace; /* workspace for pcre_dfa_exec() */
212 gint n_workspace; /* number of workspace elements */
213 const gchar *string; /* string passed to the match function */
214 gssize string_len; /* length of string */
219 volatile gint ref_count; /* the ref count for the immutable part */
220 gchar *pattern; /* the pattern */
221 pcre *pcre_re; /* compiled form of the pattern */
222 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
223 GRegexMatchFlags match_opts; /* options used at match time on the regex */
224 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
227 /* TRUE if ret is an error code, FALSE otherwise. */
228 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
230 typedef struct _InterpolationData InterpolationData;
231 static gboolean interpolation_list_needs_match (GList *list);
232 static gboolean interpolate_replacement (const GMatchInfo *match_info,
235 static GList *split_replacement (const gchar *replacement,
237 static void free_interpolation_data (InterpolationData *data);
241 match_error (gint errcode)
245 case PCRE_ERROR_NOMATCH:
248 case PCRE_ERROR_NULL:
249 /* NULL argument, this should not happen in GRegex */
250 g_warning ("A NULL argument was passed to PCRE");
252 case PCRE_ERROR_BADOPTION:
253 return "bad options";
254 case PCRE_ERROR_BADMAGIC:
255 return _("corrupted object");
256 case PCRE_ERROR_UNKNOWN_OPCODE:
257 return N_("internal error or corrupted object");
258 case PCRE_ERROR_NOMEMORY:
259 return _("out of memory");
260 case PCRE_ERROR_NOSUBSTRING:
261 /* not used by pcre_exec() */
263 case PCRE_ERROR_MATCHLIMIT:
264 return _("backtracking limit reached");
265 case PCRE_ERROR_CALLOUT:
266 /* callouts are not implemented */
268 case PCRE_ERROR_BADUTF8:
269 case PCRE_ERROR_BADUTF8_OFFSET:
270 /* we do not check if strings are valid */
272 case PCRE_ERROR_PARTIAL:
275 case PCRE_ERROR_BADPARTIAL:
276 return _("the pattern contains items not supported for partial matching");
277 case PCRE_ERROR_INTERNAL:
278 return _("internal error");
279 case PCRE_ERROR_BADCOUNT:
280 /* negative ovecsize, this should not happen in GRegex */
281 g_warning ("A negative ovecsize was passed to PCRE");
283 case PCRE_ERROR_DFA_UITEM:
284 return _("the pattern contains items not supported for partial matching");
285 case PCRE_ERROR_DFA_UCOND:
286 return _("back references as conditions are not supported for partial matching");
287 case PCRE_ERROR_DFA_UMLIMIT:
288 /* the match_field field is not used in GRegex */
290 case PCRE_ERROR_DFA_WSSIZE:
291 /* handled expanding the workspace */
293 case PCRE_ERROR_DFA_RECURSE:
294 case PCRE_ERROR_RECURSIONLIMIT:
295 return _("recursion limit reached");
296 case PCRE_ERROR_BADNEWLINE:
297 return _("invalid combination of newline flags");
298 case PCRE_ERROR_BADOFFSET:
299 return _("bad offset");
300 case PCRE_ERROR_SHORTUTF8:
301 return _("short utf8");
302 case PCRE_ERROR_RECURSELOOP:
303 return _("recursion loop");
307 return _("unknown error");
311 translate_compile_error (gint *errcode, const gchar **errmsg)
313 /* Compile errors are created adding 100 to the error code returned
315 * If errcode is known we put the translatable error message in
316 * erromsg. If errcode is unknown we put the generic
317 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
318 * untranslated error message returned by PCRE.
319 * Note that there can be more PCRE errors with the same GRegexError
320 * and that some PCRE errors are useless for us.
326 case G_REGEX_ERROR_STRAY_BACKSLASH:
327 *errmsg = _("\\ at end of pattern");
329 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
330 *errmsg = _("\\c at end of pattern");
332 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
333 *errmsg = _("unrecognized character follows \\");
335 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
336 *errmsg = _("numbers out of order in {} quantifier");
338 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
339 *errmsg = _("number too big in {} quantifier");
341 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
342 *errmsg = _("missing terminating ] for character class");
344 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
345 *errmsg = _("invalid escape sequence in character class");
347 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
348 *errmsg = _("range out of order in character class");
350 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
351 *errmsg = _("nothing to repeat");
353 case 111: /* internal error: unexpected repeat */
354 *errcode = G_REGEX_ERROR_INTERNAL;
355 *errmsg = _("unexpected repeat");
357 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
358 *errmsg = _("unrecognized character after (? or (?-");
360 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
361 *errmsg = _("POSIX named classes are supported only within a class");
363 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
364 *errmsg = _("missing terminating )");
366 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
367 *errmsg = _("reference to non-existent subpattern");
369 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
370 *errmsg = _("missing ) after comment");
372 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
373 *errmsg = _("regular expression is too large");
375 case G_REGEX_ERROR_MEMORY_ERROR:
376 *errmsg = _("failed to get memory");
378 case 122: /* unmatched parentheses */
379 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
380 *errmsg = _(") without opening (");
382 case 123: /* internal error: code overflow */
383 *errcode = G_REGEX_ERROR_INTERNAL;
384 *errmsg = _("code overflow");
386 case 124: /* "unrecognized character after (?<\0 */
387 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
388 *errmsg = _("unrecognized character after (?<");
390 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
391 *errmsg = _("lookbehind assertion is not fixed length");
393 case G_REGEX_ERROR_MALFORMED_CONDITION:
394 *errmsg = _("malformed number or name after (?(");
396 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
397 *errmsg = _("conditional group contains more than two branches");
399 case G_REGEX_ERROR_ASSERTION_EXPECTED:
400 *errmsg = _("assertion expected after (?(");
403 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
404 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
405 * sequences here, '(?-54' would be an example for the second group.
407 *errmsg = _("(?R or (?[+-]digits must be followed by )");
409 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
410 *errmsg = _("unknown POSIX class name");
412 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
413 *errmsg = _("POSIX collating elements are not supported");
415 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
416 *errmsg = _("character value in \\x{...} sequence is too large");
418 case G_REGEX_ERROR_INVALID_CONDITION:
419 *errmsg = _("invalid condition (?(0)");
421 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
422 *errmsg = _("\\C not allowed in lookbehind assertion");
424 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
425 /* A number of Perl escapes are not handled by PCRE.
426 * Therefore it explicitly raises ERR37.
428 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
429 *errmsg = _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
431 case G_REGEX_ERROR_INFINITE_LOOP:
432 *errmsg = _("recursive call could loop indefinitely");
434 case 141: /* unrecognized character after (?P\0 */
435 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
436 *errmsg = _("unrecognized character after (?P");
438 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
439 *errmsg = _("missing terminator in subpattern name");
441 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
442 *errmsg = _("two named subpatterns have the same name");
444 case G_REGEX_ERROR_MALFORMED_PROPERTY:
445 *errmsg = _("malformed \\P or \\p sequence");
447 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
448 *errmsg = _("unknown property name after \\P or \\p");
450 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
451 *errmsg = _("subpattern name is too long (maximum 32 characters)");
453 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
454 *errmsg = _("too many named subpatterns (maximum 10,000)");
456 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
457 *errmsg = _("octal value is greater than \\377");
459 case 152: /* internal error: overran compiling workspace */
460 *errcode = G_REGEX_ERROR_INTERNAL;
461 *errmsg = _("overran compiling workspace");
463 case 153: /* internal error: previously-checked referenced subpattern not found */
464 *errcode = G_REGEX_ERROR_INTERNAL;
465 *errmsg = _("previously-checked referenced subpattern not found");
467 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
468 *errmsg = _("DEFINE group contains more than one branch");
470 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
471 *errmsg = _("inconsistent NEWLINE options");
473 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
474 *errmsg = _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
475 "number, or by a plain number");
477 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE:
478 *errmsg = _("a numbered reference must not be zero");
480 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
481 *errmsg = _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
483 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB:
484 *errmsg = _("(*VERB) not recognized");
486 case G_REGEX_ERROR_NUMBER_TOO_BIG:
487 *errmsg = _("number is too bug");
489 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME:
490 *errmsg = _("missing subpattern name after (?&");
492 case G_REGEX_ERROR_MISSING_DIGIT:
493 *errmsg = _("digit expected after (?+");
495 case G_REGEX_ERROR_INVALID_DATA_CHARACTER:
496 *errmsg = _("] is an invalid data character in JavaScript compatibility mode");
498 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME:
499 *errmsg = _("different names for subpatterns of the same number are not allowed");
501 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
502 *errmsg = _("(*MARK) must have an argument");
504 case G_REGEX_ERROR_INVALID_CONTROL_CHAR:
505 *errmsg = _( "\\c must be followed by an ASCII character");
507 case G_REGEX_ERROR_MISSING_NAME:
508 *errmsg = _("\\k is not followed by a braced, angle-bracketed, or quoted name");
510 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS:
511 *errmsg = _("\\N is not supported in a class");
513 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES:
514 *errmsg = _("too many forward references");
516 case G_REGEX_ERROR_NAME_TOO_LONG:
517 *errmsg = _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
520 case 116: /* erroffset passed as NULL */
521 /* This should not happen as we never pass a NULL erroffset */
522 g_warning ("erroffset passed as NULL");
523 *errcode = G_REGEX_ERROR_COMPILE;
525 case 117: /* unknown option bit(s) set */
526 /* This should not happen as we check options before passing them
527 * to pcre_compile2() */
528 g_warning ("unknown option bit(s) set");
529 *errcode = G_REGEX_ERROR_COMPILE;
531 case 132: /* this version of PCRE is compiled without UTF support */
532 case 144: /* invalid UTF-8 string */
533 case 145: /* support for \\P, \\p, and \\X has not been compiled */
534 case 167: /* this version of PCRE is not compiled with Unicode property support */
535 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
536 case 174: /* invalid UTF-16 string */
537 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
538 * and we do not check if strings are valid */
539 case 170: /* internal error: unknown opcode in find_fixedlength() */
540 *errcode = G_REGEX_ERROR_INTERNAL;
544 *errcode = G_REGEX_ERROR_COMPILE;
551 match_info_new (const GRegex *regex,
558 GMatchInfo *match_info;
561 string_len = strlen (string);
563 match_info = g_new0 (GMatchInfo, 1);
564 match_info->ref_count = 1;
565 match_info->regex = g_regex_ref ((GRegex *)regex);
566 match_info->string = string;
567 match_info->string_len = string_len;
568 match_info->matches = PCRE_ERROR_NOMATCH;
569 match_info->pos = start_position;
570 match_info->match_opts = match_options;
574 /* These values should be enough for most cases, if they are not
575 * enough g_regex_match_all_full() will expand them. */
576 match_info->n_offsets = 24;
577 match_info->n_workspace = 100;
578 match_info->workspace = g_new (gint, match_info->n_workspace);
583 pcre_fullinfo (regex->pcre_re, regex->extra,
584 PCRE_INFO_CAPTURECOUNT, &capture_count);
585 match_info->n_offsets = (capture_count + 1) * 3;
588 match_info->offsets = g_new0 (gint, match_info->n_offsets);
589 /* Set an invalid position for the previous match. */
590 match_info->offsets[0] = -1;
591 match_info->offsets[1] = -1;
597 * g_match_info_get_regex:
598 * @match_info: a #GMatchInfo
600 * Returns #GRegex object used in @match_info. It belongs to Glib
601 * and must not be freed. Use g_regex_ref() if you need to keep it
602 * after you free @match_info object.
604 * Returns: #GRegex object used in @match_info
609 g_match_info_get_regex (const GMatchInfo *match_info)
611 g_return_val_if_fail (match_info != NULL, NULL);
612 return match_info->regex;
616 * g_match_info_get_string:
617 * @match_info: a #GMatchInfo
619 * Returns the string searched with @match_info. This is the
620 * string passed to g_regex_match() or g_regex_replace() so
621 * you may not free it before calling this function.
623 * Returns: the string searched with @match_info
628 g_match_info_get_string (const GMatchInfo *match_info)
630 g_return_val_if_fail (match_info != NULL, NULL);
631 return match_info->string;
636 * @match_info: a #GMatchInfo
638 * Increases reference count of @match_info by 1.
640 * Returns: @match_info
645 g_match_info_ref (GMatchInfo *match_info)
647 g_return_val_if_fail (match_info != NULL, NULL);
648 g_atomic_int_inc (&match_info->ref_count);
653 * g_match_info_unref:
654 * @match_info: a #GMatchInfo
656 * Decreases reference count of @match_info by 1. When reference count drops
657 * to zero, it frees all the memory associated with the match_info structure.
662 g_match_info_unref (GMatchInfo *match_info)
664 if (g_atomic_int_dec_and_test (&match_info->ref_count))
666 g_regex_unref (match_info->regex);
667 g_free (match_info->offsets);
668 g_free (match_info->workspace);
675 * @match_info: (allow-none): a #GMatchInfo, or %NULL
677 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
683 g_match_info_free (GMatchInfo *match_info)
685 if (match_info == NULL)
688 g_match_info_unref (match_info);
693 * @match_info: a #GMatchInfo structure
694 * @error: location to store the error occurring, or %NULL to ignore errors
696 * Scans for the next match using the same parameters of the previous
697 * call to g_regex_match_full() or g_regex_match() that returned
700 * The match is done on the string passed to the match function, so you
701 * cannot free it before calling this function.
703 * Returns: %TRUE is the string matched, %FALSE otherwise
708 g_match_info_next (GMatchInfo *match_info,
711 gint prev_match_start;
714 g_return_val_if_fail (match_info != NULL, FALSE);
715 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
716 g_return_val_if_fail (match_info->pos >= 0, FALSE);
718 prev_match_start = match_info->offsets[0];
719 prev_match_end = match_info->offsets[1];
721 if (match_info->pos > match_info->string_len)
723 /* we have reached the end of the string */
724 match_info->pos = -1;
725 match_info->matches = PCRE_ERROR_NOMATCH;
729 match_info->matches = pcre_exec (match_info->regex->pcre_re,
730 match_info->regex->extra,
732 match_info->string_len,
734 match_info->regex->match_opts | match_info->match_opts,
736 match_info->n_offsets);
737 if (IS_PCRE_ERROR (match_info->matches))
739 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
740 _("Error while matching regular expression %s: %s"),
741 match_info->regex->pattern, match_error (match_info->matches));
745 /* avoid infinite loops if the pattern is an empty string or something
747 if (match_info->pos == match_info->offsets[1])
749 if (match_info->pos > match_info->string_len)
751 /* we have reached the end of the string */
752 match_info->pos = -1;
753 match_info->matches = PCRE_ERROR_NOMATCH;
757 match_info->pos = NEXT_CHAR (match_info->regex,
758 &match_info->string[match_info->pos]) -
763 match_info->pos = match_info->offsets[1];
766 /* it's possible to get two identical matches when we are matching
767 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
768 * the string is "RegExTest" we have:
769 * - search at position 0: match from 0 to 0
770 * - search at position 1: match from 3 to 3
771 * - search at position 3: match from 3 to 3 (duplicate)
772 * - search at position 4: match from 5 to 5
773 * - search at position 5: match from 5 to 5 (duplicate)
774 * - search at position 6: no match -> stop
775 * so we have to ignore the duplicates.
776 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
777 if (match_info->matches >= 0 &&
778 prev_match_start == match_info->offsets[0] &&
779 prev_match_end == match_info->offsets[1])
781 /* ignore this match and search the next one */
782 return g_match_info_next (match_info, error);
785 return match_info->matches >= 0;
789 * g_match_info_matches:
790 * @match_info: a #GMatchInfo structure
792 * Returns whether the previous match operation succeeded.
794 * Returns: %TRUE if the previous match operation succeeded,
800 g_match_info_matches (const GMatchInfo *match_info)
802 g_return_val_if_fail (match_info != NULL, FALSE);
804 return match_info->matches >= 0;
808 * g_match_info_get_match_count:
809 * @match_info: a #GMatchInfo structure
811 * Retrieves the number of matched substrings (including substring 0,
812 * that is the whole matched text), so 1 is returned if the pattern
813 * has no substrings in it and 0 is returned if the match failed.
815 * If the last match was obtained using the DFA algorithm, that is
816 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
817 * count is not that of the number of capturing parentheses but that of
818 * the number of matched substrings.
820 * Returns: Number of matched substrings, or -1 if an error occurred
825 g_match_info_get_match_count (const GMatchInfo *match_info)
827 g_return_val_if_fail (match_info, -1);
829 if (match_info->matches == PCRE_ERROR_NOMATCH)
832 else if (match_info->matches < PCRE_ERROR_NOMATCH)
837 return match_info->matches;
841 * g_match_info_is_partial_match:
842 * @match_info: a #GMatchInfo structure
844 * Usually if the string passed to g_regex_match*() matches as far as
845 * it goes, but is too short to match the entire pattern, %FALSE is
846 * returned. There are circumstances where it might be helpful to
847 * distinguish this case from other cases in which there is no match.
849 * Consider, for example, an application where a human is required to
850 * type in data for a field with specific formatting requirements. An
851 * example might be a date in the form ddmmmyy, defined by the pattern
852 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
853 * If the application sees the user’s keystrokes one by one, and can
854 * check that what has been typed so far is potentially valid, it is
855 * able to raise an error as soon as a mistake is made.
857 * GRegex supports the concept of partial matching by means of the
858 * #G_REGEX_MATCH_PARTIAL_SOFT and #G_REGEX_MATCH_PARTIAL_HARD flags.
859 * When they are used, the return code for
860 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
861 * for a complete match, %FALSE otherwise. But, when these functions
862 * return %FALSE, you can check if the match was partial calling
863 * g_match_info_is_partial_match().
865 * The difference between #G_REGEX_MATCH_PARTIAL_SOFT and
866 * #G_REGEX_MATCH_PARTIAL_HARD is that when a partial match is encountered
867 * with #G_REGEX_MATCH_PARTIAL_SOFT, matching continues to search for a
868 * possible complete match, while with #G_REGEX_MATCH_PARTIAL_HARD matching
869 * stops at the partial match.
870 * When both #G_REGEX_MATCH_PARTIAL_SOFT and #G_REGEX_MATCH_PARTIAL_HARD
871 * are set, the latter takes precedence.
872 * See <ulink>man:pcrepartial</ulink> for more information on partial matching.
874 * Because of the way certain internal optimizations are implemented
875 * the partial matching algorithm cannot be used with all patterns.
876 * So repeated single characters such as "a{2,4}" and repeated single
877 * meta-sequences such as "\d+" are not permitted if the maximum number
878 * of occurrences is greater than one. Optional items such as "\d?"
879 * (where the maximum is one) are permitted. Quantifiers with any values
880 * are permitted after parentheses, so the invalid examples above can be
881 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL or
882 * #G_REGEX_MATCH_PARTIAL_HARD is set
883 * for a pattern that does not conform to the restrictions, matching
884 * functions return an error.
886 * Returns: %TRUE if the match was partial, %FALSE otherwise
891 g_match_info_is_partial_match (const GMatchInfo *match_info)
893 g_return_val_if_fail (match_info != NULL, FALSE);
895 return match_info->matches == PCRE_ERROR_PARTIAL;
899 * g_match_info_expand_references:
900 * @match_info: (allow-none): a #GMatchInfo or %NULL
901 * @string_to_expand: the string to expand
902 * @error: location to store the error occurring, or %NULL to ignore errors
904 * Returns a new string containing the text in @string_to_expand with
905 * references and escape sequences expanded. References refer to the last
906 * match done with @string against @regex and have the same syntax used by
909 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
910 * passed to g_regex_new().
912 * The backreferences are extracted from the string passed to the match
913 * function, so you cannot call this function after freeing the string.
915 * @match_info may be %NULL in which case @string_to_expand must not
916 * contain references. For instance "foo\n" does not refer to an actual
917 * pattern and '\n' merely will be replaced with \n character,
918 * while to expand "\0" (whole match) one needs the result of a match.
919 * Use g_regex_check_replacement() to find out whether @string_to_expand
920 * contains references.
922 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
927 g_match_info_expand_references (const GMatchInfo *match_info,
928 const gchar *string_to_expand,
933 GError *tmp_error = NULL;
935 g_return_val_if_fail (string_to_expand != NULL, NULL);
936 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
938 list = split_replacement (string_to_expand, &tmp_error);
939 if (tmp_error != NULL)
941 g_propagate_error (error, tmp_error);
945 if (!match_info && interpolation_list_needs_match (list))
947 g_critical ("String '%s' contains references to the match, can't "
948 "expand references without GMatchInfo object",
953 result = g_string_sized_new (strlen (string_to_expand));
954 interpolate_replacement (match_info, result, list);
956 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
958 return g_string_free (result, FALSE);
962 * g_match_info_fetch:
963 * @match_info: #GMatchInfo structure
964 * @match_num: number of the sub expression
966 * Retrieves the text matching the @match_num<!-- -->'th capturing
967 * parentheses. 0 is the full text of the match, 1 is the first paren
968 * set, 2 the second, and so on.
970 * If @match_num is a valid sub pattern but it didn't match anything
971 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
972 * string is returned.
974 * If the match was obtained using the DFA algorithm, that is using
975 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
976 * string is not that of a set of parentheses but that of a matched
977 * substring. Substrings are matched in reverse order of length, so
978 * 0 is the longest match.
980 * The string is fetched from the string passed to the match function,
981 * so you cannot call this function after freeing the string.
983 * Returns: (allow-none): The matched substring, or %NULL if an error
984 * occurred. You have to free the string yourself
989 g_match_info_fetch (const GMatchInfo *match_info,
992 /* we cannot use pcre_get_substring() because it allocates the
993 * string using pcre_malloc(). */
997 g_return_val_if_fail (match_info != NULL, NULL);
998 g_return_val_if_fail (match_num >= 0, NULL);
1000 /* match_num does not exist or it didn't matched, i.e. matching "b"
1001 * against "(a)?b" then group 0 is empty. */
1002 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
1004 else if (start == -1)
1005 match = g_strdup ("");
1007 match = g_strndup (&match_info->string[start], end - start);
1013 * g_match_info_fetch_pos:
1014 * @match_info: #GMatchInfo structure
1015 * @match_num: number of the sub expression
1016 * @start_pos: (out) (allow-none): pointer to location where to store
1017 * the start position, or %NULL
1018 * @end_pos: (out) (allow-none): pointer to location where to store
1019 * the end position, or %NULL
1021 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
1022 * parentheses. 0 is the full text of the match, 1 is the first
1023 * paren set, 2 the second, and so on.
1025 * If @match_num is a valid sub pattern but it didn't match anything
1026 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
1027 * and @end_pos are set to -1 and %TRUE is returned.
1029 * If the match was obtained using the DFA algorithm, that is using
1030 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1031 * position is not that of a set of parentheses but that of a matched
1032 * substring. Substrings are matched in reverse order of length, so
1033 * 0 is the longest match.
1035 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
1036 * the position cannot be fetched, @start_pos and @end_pos are left
1042 g_match_info_fetch_pos (const GMatchInfo *match_info,
1047 g_return_val_if_fail (match_info != NULL, FALSE);
1048 g_return_val_if_fail (match_num >= 0, FALSE);
1050 /* make sure the sub expression number they're requesting is less than
1051 * the total number of sub expressions that were matched. */
1052 if (match_num >= match_info->matches)
1055 if (start_pos != NULL)
1056 *start_pos = match_info->offsets[2 * match_num];
1058 if (end_pos != NULL)
1059 *end_pos = match_info->offsets[2 * match_num + 1];
1065 * Returns number of first matched subpattern with name @name.
1066 * There may be more than one in case when DUPNAMES is used,
1067 * and not all subpatterns with that name match;
1068 * pcre_get_stringnumber() does not work in that case.
1071 get_matched_substring_number (const GMatchInfo *match_info,
1075 gchar *first, *last;
1078 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
1079 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
1081 /* This code is copied from pcre_get.c: get_first_set() */
1082 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
1090 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
1092 gint n = (entry[0] << 8) + entry[1];
1093 if (match_info->offsets[n*2] >= 0)
1097 return (first[0] << 8) + first[1];
1101 * g_match_info_fetch_named:
1102 * @match_info: #GMatchInfo structure
1103 * @name: name of the subexpression
1105 * Retrieves the text matching the capturing parentheses named @name.
1107 * If @name is a valid sub pattern name but it didn't match anything
1108 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1109 * then an empty string is returned.
1111 * The string is fetched from the string passed to the match function,
1112 * so you cannot call this function after freeing the string.
1114 * Returns: (allow-none): The matched substring, or %NULL if an error
1115 * occurred. You have to free the string yourself
1120 g_match_info_fetch_named (const GMatchInfo *match_info,
1123 /* we cannot use pcre_get_named_substring() because it allocates the
1124 * string using pcre_malloc(). */
1127 g_return_val_if_fail (match_info != NULL, NULL);
1128 g_return_val_if_fail (name != NULL, NULL);
1130 num = get_matched_substring_number (match_info, name);
1134 return g_match_info_fetch (match_info, num);
1138 * g_match_info_fetch_named_pos:
1139 * @match_info: #GMatchInfo structure
1140 * @name: name of the subexpression
1141 * @start_pos: (out) (allow-none): pointer to location where to store
1142 * the start position, or %NULL
1143 * @end_pos: (out) (allow-none): pointer to location where to store
1144 * the end position, or %NULL
1146 * Retrieves the position in bytes of the capturing parentheses named @name.
1148 * If @name is a valid sub pattern name but it didn't match anything
1149 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1150 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1152 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1153 * If the position cannot be fetched, @start_pos and @end_pos
1154 * are left unchanged.
1159 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
1166 g_return_val_if_fail (match_info != NULL, FALSE);
1167 g_return_val_if_fail (name != NULL, FALSE);
1169 num = get_matched_substring_number (match_info, name);
1173 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
1177 * g_match_info_fetch_all:
1178 * @match_info: a #GMatchInfo structure
1180 * Bundles up pointers to each of the matching substrings from a match
1181 * and stores them in an array of gchar pointers. The first element in
1182 * the returned array is the match number 0, i.e. the entire matched
1185 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1186 * "b" against "(a)?b") then an empty string is inserted.
1188 * If the last match was obtained using the DFA algorithm, that is using
1189 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1190 * strings are not that matched by sets of parentheses but that of the
1191 * matched substring. Substrings are matched in reverse order of length,
1192 * so the first one is the longest match.
1194 * The strings are fetched from the string passed to the match function,
1195 * so you cannot call this function after freeing the string.
1197 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
1198 * It must be freed using g_strfreev(). If the previous match failed
1204 g_match_info_fetch_all (const GMatchInfo *match_info)
1206 /* we cannot use pcre_get_substring_list() because the returned value
1207 * isn't suitable for g_strfreev(). */
1211 g_return_val_if_fail (match_info != NULL, NULL);
1213 if (match_info->matches < 0)
1216 result = g_new (gchar *, match_info->matches + 1);
1217 for (i = 0; i < match_info->matches; i++)
1218 result[i] = g_match_info_fetch (match_info, i);
1228 g_regex_error_quark (void)
1230 static GQuark error_quark = 0;
1232 if (error_quark == 0)
1233 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1242 * Increases reference count of @regex by 1.
1249 g_regex_ref (GRegex *regex)
1251 g_return_val_if_fail (regex != NULL, NULL);
1252 g_atomic_int_inc (®ex->ref_count);
1260 * Decreases reference count of @regex by 1. When reference count drops
1261 * to zero, it frees all the memory associated with the regex structure.
1266 g_regex_unref (GRegex *regex)
1268 g_return_if_fail (regex != NULL);
1270 if (g_atomic_int_dec_and_test (®ex->ref_count))
1272 g_free (regex->pattern);
1273 if (regex->pcre_re != NULL)
1274 pcre_free (regex->pcre_re);
1275 if (regex->extra != NULL)
1276 pcre_free (regex->extra);
1283 * @pattern: the regular expression
1284 * @compile_options: compile options for the regular expression, or 0
1285 * @match_options: match options for the regular expression, or 0
1286 * @error: return location for a #GError
1288 * Compiles the regular expression to an internal form, and does
1289 * the initial setup of the #GRegex structure.
1291 * Returns: a #GRegex structure. Call g_regex_unref() when you
1297 g_regex_new (const gchar *pattern,
1298 GRegexCompileFlags compile_options,
1299 GRegexMatchFlags match_options,
1304 const gchar *errmsg;
1307 gboolean optimize = FALSE;
1308 static volatile gsize initialised = 0;
1309 unsigned long int pcre_compile_options;
1310 GRegexCompileFlags nonpcre_compile_options;
1312 g_return_val_if_fail (pattern != NULL, NULL);
1313 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1314 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1315 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1317 if (g_once_init_enter (&initialised))
1319 int supports_utf8, supports_ucp;
1321 pcre_config (PCRE_CONFIG_UTF8, &supports_utf8);
1323 g_critical (_("PCRE library is compiled without UTF8 support"));
1325 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &supports_ucp);
1327 g_critical (_("PCRE library is compiled without UTF8 properties support"));
1329 g_once_init_leave (&initialised, supports_utf8 && supports_ucp ? 1 : 2);
1332 if (G_UNLIKELY (initialised != 1))
1334 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE,
1335 _("PCRE library is compiled with incompatible options"));
1339 nonpcre_compile_options = compile_options & G_REGEX_COMPILE_NONPCRE_MASK;
1341 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1342 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1343 if (compile_options & G_REGEX_OPTIMIZE)
1346 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1347 * instead uses UTF-8 only if required with PCRE_UTF8. */
1348 if (compile_options & G_REGEX_RAW)
1351 compile_options &= ~G_REGEX_RAW;
1356 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1357 match_options |= PCRE_NO_UTF8_CHECK;
1360 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1361 * not for the system one. */
1362 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1363 !(compile_options & G_REGEX_NEWLINE_LF))
1365 compile_options |= PCRE_NEWLINE_ANY;
1368 compile_options |= PCRE_UCP;
1370 /* PCRE_BSR_UNICODE is the default for the internal PCRE but
1371 * possibly not for the system one.
1373 if (~compile_options & G_REGEX_BSR_ANYCRLF)
1374 compile_options |= PCRE_BSR_UNICODE;
1376 /* compile the pattern */
1377 re = pcre_compile2 (pattern, compile_options, &errcode,
1378 &errmsg, &erroffset, NULL);
1380 /* if the compilation failed, set the error member and return
1386 /* Translate the PCRE error code to GRegexError and use a translated
1387 * error message if possible */
1388 translate_compile_error (&errcode, &errmsg);
1390 /* PCRE uses byte offsets but we want to show character offsets */
1391 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1393 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1394 _("Error while compiling regular "
1395 "expression %s at char %d: %s"),
1396 pattern, erroffset, errmsg);
1397 g_propagate_error (error, tmp_error);
1402 /* For options set at the beginning of the pattern, pcre puts them into
1403 * compile options, e.g. "(?i)foo" will make the pcre structure store
1404 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1405 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1406 compile_options = pcre_compile_options & G_REGEX_COMPILE_PCRE_MASK;
1408 /* Don't leak PCRE_NEWLINE_ANY, which is part of PCRE_NEWLINE_ANYCRLF */
1409 if ((pcre_compile_options & PCRE_NEWLINE_ANYCRLF) != PCRE_NEWLINE_ANYCRLF)
1410 compile_options &= ~PCRE_NEWLINE_ANY;
1412 compile_options |= nonpcre_compile_options;
1414 if (!(compile_options & G_REGEX_DUPNAMES))
1416 gboolean jchanged = FALSE;
1417 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1419 compile_options |= G_REGEX_DUPNAMES;
1422 regex = g_new0 (GRegex, 1);
1423 regex->ref_count = 1;
1424 regex->pattern = g_strdup (pattern);
1425 regex->pcre_re = re;
1426 regex->compile_opts = compile_options;
1427 regex->match_opts = match_options;
1431 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1434 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1435 G_REGEX_ERROR_OPTIMIZE,
1436 _("Error while optimizing "
1437 "regular expression %s: %s"),
1440 g_propagate_error (error, tmp_error);
1442 g_regex_unref (regex);
1451 * g_regex_get_pattern:
1452 * @regex: a #GRegex structure
1454 * Gets the pattern string associated with @regex, i.e. a copy of
1455 * the string passed to g_regex_new().
1457 * Returns: the pattern of @regex
1462 g_regex_get_pattern (const GRegex *regex)
1464 g_return_val_if_fail (regex != NULL, NULL);
1466 return regex->pattern;
1470 * g_regex_get_max_backref:
1473 * Returns the number of the highest back reference
1474 * in the pattern, or 0 if the pattern does not contain
1477 * Returns: the number of the highest back reference
1482 g_regex_get_max_backref (const GRegex *regex)
1486 pcre_fullinfo (regex->pcre_re, regex->extra,
1487 PCRE_INFO_BACKREFMAX, &value);
1493 * g_regex_get_capture_count:
1496 * Returns the number of capturing subpatterns in the pattern.
1498 * Returns: the number of capturing subpatterns
1503 g_regex_get_capture_count (const GRegex *regex)
1507 pcre_fullinfo (regex->pcre_re, regex->extra,
1508 PCRE_INFO_CAPTURECOUNT, &value);
1514 * g_regex_get_has_cr_or_lf:
1515 * @regex: a #GRegex structure
1517 * Checks whether the pattern contains explicit CR or LF references.
1519 * Returns: %TRUE if the pattern contains explicit CR or LF references
1524 g_regex_get_has_cr_or_lf (const GRegex *regex)
1528 pcre_fullinfo (regex->pcre_re, regex->extra,
1529 PCRE_INFO_HASCRORLF, &value);
1535 * g_regex_get_compile_flags:
1538 * Returns the compile options that @regex was created with.
1540 * Returns: flags from #GRegexCompileFlags
1545 g_regex_get_compile_flags (const GRegex *regex)
1547 g_return_val_if_fail (regex != NULL, 0);
1549 return regex->compile_opts;
1553 * g_regex_get_match_flags:
1556 * Returns the match options that @regex was created with.
1558 * Returns: flags from #GRegexMatchFlags
1563 g_regex_get_match_flags (const GRegex *regex)
1565 g_return_val_if_fail (regex != NULL, 0);
1567 return regex->match_opts & G_REGEX_MATCH_MASK;
1571 * g_regex_match_simple:
1572 * @pattern: the regular expression
1573 * @string: the string to scan for matches
1574 * @compile_options: compile options for the regular expression, or 0
1575 * @match_options: match options, or 0
1577 * Scans for a match in @string for @pattern.
1579 * This function is equivalent to g_regex_match() but it does not
1580 * require to compile the pattern with g_regex_new(), avoiding some
1581 * lines of code when you need just to do a match without extracting
1582 * substrings, capture counts, and so on.
1584 * If this function is to be called on the same @pattern more than
1585 * once, it's more efficient to compile the pattern once with
1586 * g_regex_new() and then use g_regex_match().
1588 * Returns: %TRUE if the string matched, %FALSE otherwise
1593 g_regex_match_simple (const gchar *pattern,
1594 const gchar *string,
1595 GRegexCompileFlags compile_options,
1596 GRegexMatchFlags match_options)
1601 regex = g_regex_new (pattern, compile_options, 0, NULL);
1604 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1605 g_regex_unref (regex);
1611 * @regex: a #GRegex structure from g_regex_new()
1612 * @string: the string to scan for matches
1613 * @match_options: match options
1614 * @match_info: (out) (allow-none): pointer to location where to store
1615 * the #GMatchInfo, or %NULL if you do not need it
1617 * Scans for a match in string for the pattern in @regex.
1618 * The @match_options are combined with the match options specified
1619 * when the @regex structure was created, letting you have more
1620 * flexibility in reusing #GRegex structures.
1622 * A #GMatchInfo structure, used to get information on the match,
1623 * is stored in @match_info if not %NULL. Note that if @match_info
1624 * is not %NULL then it is created even if the function returns %FALSE,
1625 * i.e. you must free it regardless if regular expression actually matched.
1627 * To retrieve all the non-overlapping matches of the pattern in
1628 * string you can use g_match_info_next().
1632 * print_uppercase_words (const gchar *string)
1634 * /* Print all uppercase-only words. */
1636 * GMatchInfo *match_info;
1638 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1639 * g_regex_match (regex, string, 0, &match_info);
1640 * while (g_match_info_matches (match_info))
1642 * gchar *word = g_match_info_fetch (match_info, 0);
1643 * g_print ("Found: %s\n", word);
1645 * g_match_info_next (match_info, NULL);
1647 * g_match_info_free (match_info);
1648 * g_regex_unref (regex);
1652 * @string is not copied and is used in #GMatchInfo internally. If
1653 * you use any #GMatchInfo method (except g_match_info_free()) after
1654 * freeing or modifying @string then the behaviour is undefined.
1656 * Returns: %TRUE is the string matched, %FALSE otherwise
1661 g_regex_match (const GRegex *regex,
1662 const gchar *string,
1663 GRegexMatchFlags match_options,
1664 GMatchInfo **match_info)
1666 return g_regex_match_full (regex, string, -1, 0, match_options,
1671 * g_regex_match_full:
1672 * @regex: a #GRegex structure from g_regex_new()
1673 * @string: (array length=string_len): the string to scan for matches
1674 * @string_len: the length of @string, or -1 if @string is nul-terminated
1675 * @start_position: starting index of the string to match
1676 * @match_options: match options
1677 * @match_info: (out) (allow-none): pointer to location where to store
1678 * the #GMatchInfo, or %NULL if you do not need it
1679 * @error: location to store the error occurring, or %NULL to ignore errors
1681 * Scans for a match in string for the pattern in @regex.
1682 * The @match_options are combined with the match options specified
1683 * when the @regex structure was created, letting you have more
1684 * flexibility in reusing #GRegex structures.
1686 * Setting @start_position differs from just passing over a shortened
1687 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1688 * that begins with any kind of lookbehind assertion, such as "\b".
1690 * A #GMatchInfo structure, used to get information on the match, is
1691 * stored in @match_info if not %NULL. Note that if @match_info is
1692 * not %NULL then it is created even if the function returns %FALSE,
1693 * i.e. you must free it regardless if regular expression actually
1696 * @string is not copied and is used in #GMatchInfo internally. If
1697 * you use any #GMatchInfo method (except g_match_info_free()) after
1698 * freeing or modifying @string then the behaviour is undefined.
1700 * To retrieve all the non-overlapping matches of the pattern in
1701 * string you can use g_match_info_next().
1705 * print_uppercase_words (const gchar *string)
1707 * /* Print all uppercase-only words. */
1709 * GMatchInfo *match_info;
1710 * GError *error = NULL;
1712 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1713 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1714 * while (g_match_info_matches (match_info))
1716 * gchar *word = g_match_info_fetch (match_info, 0);
1717 * g_print ("Found: %s\n", word);
1719 * g_match_info_next (match_info, &error);
1721 * g_match_info_free (match_info);
1722 * g_regex_unref (regex);
1723 * if (error != NULL)
1725 * g_printerr ("Error while matching: %s\n", error->message);
1726 * g_error_free (error);
1731 * Returns: %TRUE is the string matched, %FALSE otherwise
1736 g_regex_match_full (const GRegex *regex,
1737 const gchar *string,
1739 gint start_position,
1740 GRegexMatchFlags match_options,
1741 GMatchInfo **match_info,
1747 g_return_val_if_fail (regex != NULL, FALSE);
1748 g_return_val_if_fail (string != NULL, FALSE);
1749 g_return_val_if_fail (start_position >= 0, FALSE);
1750 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1751 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1753 info = match_info_new (regex, string, string_len, start_position,
1754 match_options, FALSE);
1755 match_ok = g_match_info_next (info, error);
1756 if (match_info != NULL)
1759 g_match_info_free (info);
1765 * g_regex_match_all:
1766 * @regex: a #GRegex structure from g_regex_new()
1767 * @string: the string to scan for matches
1768 * @match_options: match options
1769 * @match_info: (out) (allow-none): pointer to location where to store
1770 * the #GMatchInfo, or %NULL if you do not need it
1772 * Using the standard algorithm for regular expression matching only
1773 * the longest match in the string is retrieved. This function uses
1774 * a different algorithm so it can retrieve all the possible matches.
1775 * For more documentation see g_regex_match_all_full().
1777 * A #GMatchInfo structure, used to get information on the match, is
1778 * stored in @match_info if not %NULL. Note that if @match_info is
1779 * not %NULL then it is created even if the function returns %FALSE,
1780 * i.e. you must free it regardless if regular expression actually
1783 * @string is not copied and is used in #GMatchInfo internally. If
1784 * you use any #GMatchInfo method (except g_match_info_free()) after
1785 * freeing or modifying @string then the behaviour is undefined.
1787 * Returns: %TRUE is the string matched, %FALSE otherwise
1792 g_regex_match_all (const GRegex *regex,
1793 const gchar *string,
1794 GRegexMatchFlags match_options,
1795 GMatchInfo **match_info)
1797 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1802 * g_regex_match_all_full:
1803 * @regex: a #GRegex structure from g_regex_new()
1804 * @string: (array length=string_len): the string to scan for matches
1805 * @string_len: the length of @string, or -1 if @string is nul-terminated
1806 * @start_position: starting index of the string to match
1807 * @match_options: match options
1808 * @match_info: (out) (allow-none): pointer to location where to store
1809 * the #GMatchInfo, or %NULL if you do not need it
1810 * @error: location to store the error occurring, or %NULL to ignore errors
1812 * Using the standard algorithm for regular expression matching only
1813 * the longest match in the string is retrieved, it is not possible
1814 * to obtain all the available matches. For instance matching
1815 * "<a> <b> <c>" against the pattern "<.*>"
1816 * you get "<a> <b> <c>".
1818 * This function uses a different algorithm (called DFA, i.e. deterministic
1819 * finite automaton), so it can retrieve all the possible matches, all
1820 * starting at the same point in the string. For instance matching
1821 * "<a> <b> <c>" against the pattern "<.*>"
1822 * you would obtain three matches: "<a> <b> <c>",
1823 * "<a> <b>" and "<a>".
1825 * The number of matched strings is retrieved using
1826 * g_match_info_get_match_count(). To obtain the matched strings and
1827 * their position you can use, respectively, g_match_info_fetch() and
1828 * g_match_info_fetch_pos(). Note that the strings are returned in
1829 * reverse order of length; that is, the longest matching string is
1832 * Note that the DFA algorithm is slower than the standard one and it
1833 * is not able to capture substrings, so backreferences do not work.
1835 * Setting @start_position differs from just passing over a shortened
1836 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1837 * that begins with any kind of lookbehind assertion, such as "\b".
1839 * A #GMatchInfo structure, used to get information on the match, is
1840 * stored in @match_info if not %NULL. Note that if @match_info is
1841 * not %NULL then it is created even if the function returns %FALSE,
1842 * i.e. you must free it regardless if regular expression actually
1845 * @string is not copied and is used in #GMatchInfo internally. If
1846 * you use any #GMatchInfo method (except g_match_info_free()) after
1847 * freeing or modifying @string then the behaviour is undefined.
1849 * Returns: %TRUE is the string matched, %FALSE otherwise
1854 g_regex_match_all_full (const GRegex *regex,
1855 const gchar *string,
1857 gint start_position,
1858 GRegexMatchFlags match_options,
1859 GMatchInfo **match_info,
1865 g_return_val_if_fail (regex != NULL, FALSE);
1866 g_return_val_if_fail (string != NULL, FALSE);
1867 g_return_val_if_fail (start_position >= 0, FALSE);
1868 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1869 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1871 info = match_info_new (regex, string, string_len, start_position,
1872 match_options, TRUE);
1878 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1879 info->string, info->string_len,
1881 regex->match_opts | match_options,
1882 info->offsets, info->n_offsets,
1883 info->workspace, info->n_workspace);
1884 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1886 /* info->workspace is too small. */
1887 info->n_workspace *= 2;
1888 info->workspace = g_realloc (info->workspace,
1889 info->n_workspace * sizeof (gint));
1892 else if (info->matches == 0)
1894 /* info->offsets is too small. */
1895 info->n_offsets *= 2;
1896 info->offsets = g_realloc (info->offsets,
1897 info->n_offsets * sizeof (gint));
1900 else if (IS_PCRE_ERROR (info->matches))
1902 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1903 _("Error while matching regular expression %s: %s"),
1904 regex->pattern, match_error (info->matches));
1908 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1911 if (match_info != NULL)
1914 g_match_info_free (info);
1916 return info->matches >= 0;
1920 * g_regex_get_string_number:
1921 * @regex: #GRegex structure
1922 * @name: name of the subexpression
1924 * Retrieves the number of the subexpression named @name.
1926 * Returns: The number of the subexpression or -1 if @name
1932 g_regex_get_string_number (const GRegex *regex,
1937 g_return_val_if_fail (regex != NULL, -1);
1938 g_return_val_if_fail (name != NULL, -1);
1940 num = pcre_get_stringnumber (regex->pcre_re, name);
1941 if (num == PCRE_ERROR_NOSUBSTRING)
1948 * g_regex_split_simple:
1949 * @pattern: the regular expression
1950 * @string: the string to scan for matches
1951 * @compile_options: compile options for the regular expression, or 0
1952 * @match_options: match options, or 0
1954 * Breaks the string on the pattern, and returns an array of
1955 * the tokens. If the pattern contains capturing parentheses,
1956 * then the text for each of the substrings will also be returned.
1957 * If the pattern does not match anywhere in the string, then the
1958 * whole string is returned as the first token.
1960 * This function is equivalent to g_regex_split() but it does
1961 * not require to compile the pattern with g_regex_new(), avoiding
1962 * some lines of code when you need just to do a split without
1963 * extracting substrings, capture counts, and so on.
1965 * If this function is to be called on the same @pattern more than
1966 * once, it's more efficient to compile the pattern once with
1967 * g_regex_new() and then use g_regex_split().
1969 * As a special case, the result of splitting the empty string ""
1970 * is an empty vector, not a vector containing a single string.
1971 * The reason for this special case is that being able to represent
1972 * a empty vector is typically more useful than consistent handling
1973 * of empty elements. If you do need to represent empty elements,
1974 * you'll need to check for the empty string before calling this
1977 * A pattern that can match empty strings splits @string into
1978 * separate characters wherever it matches the empty string between
1979 * characters. For example splitting "ab c" using as a separator
1980 * "\s*", you will get "a", "b" and "c".
1982 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1987 g_regex_split_simple (const gchar *pattern,
1988 const gchar *string,
1989 GRegexCompileFlags compile_options,
1990 GRegexMatchFlags match_options)
1995 regex = g_regex_new (pattern, compile_options, 0, NULL);
1999 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
2000 g_regex_unref (regex);
2006 * @regex: a #GRegex structure
2007 * @string: the string to split with the pattern
2008 * @match_options: match time option flags
2010 * Breaks the string on the pattern, and returns an array of the tokens.
2011 * If the pattern contains capturing parentheses, then the text for each
2012 * of the substrings will also be returned. If the pattern does not match
2013 * anywhere in the string, then the whole string is returned as the first
2016 * As a special case, the result of splitting the empty string "" is an
2017 * empty vector, not a vector containing a single string. The reason for
2018 * this special case is that being able to represent a empty vector is
2019 * typically more useful than consistent handling of empty elements. If
2020 * you do need to represent empty elements, you'll need to check for the
2021 * empty string before calling this function.
2023 * A pattern that can match empty strings splits @string into separate
2024 * characters wherever it matches the empty string between characters.
2025 * For example splitting "ab c" using as a separator "\s*", you will get
2028 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2033 g_regex_split (const GRegex *regex,
2034 const gchar *string,
2035 GRegexMatchFlags match_options)
2037 return g_regex_split_full (regex, string, -1, 0,
2038 match_options, 0, NULL);
2042 * g_regex_split_full:
2043 * @regex: a #GRegex structure
2044 * @string: (array length=string_len): the string to split with the pattern
2045 * @string_len: the length of @string, or -1 if @string is nul-terminated
2046 * @start_position: starting index of the string to match
2047 * @match_options: match time option flags
2048 * @max_tokens: the maximum number of tokens to split @string into.
2049 * If this is less than 1, the string is split completely
2050 * @error: return location for a #GError
2052 * Breaks the string on the pattern, and returns an array of the tokens.
2053 * If the pattern contains capturing parentheses, then the text for each
2054 * of the substrings will also be returned. If the pattern does not match
2055 * anywhere in the string, then the whole string is returned as the first
2058 * As a special case, the result of splitting the empty string "" is an
2059 * empty vector, not a vector containing a single string. The reason for
2060 * this special case is that being able to represent a empty vector is
2061 * typically more useful than consistent handling of empty elements. If
2062 * you do need to represent empty elements, you'll need to check for the
2063 * empty string before calling this function.
2065 * A pattern that can match empty strings splits @string into separate
2066 * characters wherever it matches the empty string between characters.
2067 * For example splitting "ab c" using as a separator "\s*", you will get
2070 * Setting @start_position differs from just passing over a shortened
2071 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2072 * that begins with any kind of lookbehind assertion, such as "\b".
2074 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2079 g_regex_split_full (const GRegex *regex,
2080 const gchar *string,
2082 gint start_position,
2083 GRegexMatchFlags match_options,
2087 GError *tmp_error = NULL;
2088 GMatchInfo *match_info;
2093 /* position of the last separator. */
2094 gint last_separator_end;
2095 /* was the last match 0 bytes long? */
2096 gboolean last_match_is_empty;
2097 /* the returned array of char **s */
2098 gchar **string_list;
2100 g_return_val_if_fail (regex != NULL, NULL);
2101 g_return_val_if_fail (string != NULL, NULL);
2102 g_return_val_if_fail (start_position >= 0, NULL);
2103 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2104 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2106 if (max_tokens <= 0)
2107 max_tokens = G_MAXINT;
2110 string_len = strlen (string);
2112 /* zero-length string */
2113 if (string_len - start_position == 0)
2114 return g_new0 (gchar *, 1);
2116 if (max_tokens == 1)
2118 string_list = g_new0 (gchar *, 2);
2119 string_list[0] = g_strndup (&string[start_position],
2120 string_len - start_position);
2126 last_separator_end = start_position;
2127 last_match_is_empty = FALSE;
2129 match_ok = g_regex_match_full (regex, string, string_len, start_position,
2130 match_options, &match_info, &tmp_error);
2132 while (tmp_error == NULL)
2136 last_match_is_empty =
2137 (match_info->offsets[0] == match_info->offsets[1]);
2139 /* we need to skip empty separators at the same position of the end
2140 * of another separator. e.g. the string is "a b" and the separator
2141 * is " *", so from 1 to 2 we have a match and at position 2 we have
2142 * an empty match. */
2143 if (last_separator_end != match_info->offsets[1])
2148 token = g_strndup (string + last_separator_end,
2149 match_info->offsets[0] - last_separator_end);
2150 list = g_list_prepend (list, token);
2153 /* if there were substrings, these need to be added to
2155 match_count = g_match_info_get_match_count (match_info);
2156 if (match_count > 1)
2158 for (i = 1; i < match_count; i++)
2159 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
2165 /* if there was no match, copy to end of string. */
2166 if (!last_match_is_empty)
2168 gchar *token = g_strndup (string + last_separator_end,
2169 match_info->string_len - last_separator_end);
2170 list = g_list_prepend (list, token);
2172 /* no more tokens, end the loop. */
2176 /* -1 to leave room for the last part. */
2177 if (token_count >= max_tokens - 1)
2179 /* we have reached the maximum number of tokens, so we copy
2180 * the remaining part of the string. */
2181 if (last_match_is_empty)
2183 /* the last match was empty, so we have moved one char
2184 * after the real position to avoid empty matches at the
2186 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
2188 /* the if is needed in the case we have terminated the available
2189 * tokens, but we are at the end of the string, so there are no
2190 * characters left to copy. */
2191 if (string_len > match_info->pos)
2193 gchar *token = g_strndup (string + match_info->pos,
2194 string_len - match_info->pos);
2195 list = g_list_prepend (list, token);
2201 last_separator_end = match_info->pos;
2202 if (last_match_is_empty)
2203 /* if the last match was empty, g_match_info_next() has moved
2204 * forward to avoid infinite loops, but we still need to copy that
2206 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
2208 match_ok = g_match_info_next (match_info, &tmp_error);
2210 g_match_info_free (match_info);
2211 if (tmp_error != NULL)
2213 g_propagate_error (error, tmp_error);
2214 g_list_free_full (list, g_free);
2215 match_info->pos = -1;
2219 string_list = g_new (gchar *, g_list_length (list) + 1);
2221 for (last = g_list_last (list); last; last = g_list_previous (last))
2222 string_list[i++] = last->data;
2223 string_list[i] = NULL;
2232 REPL_TYPE_CHARACTER,
2233 REPL_TYPE_SYMBOLIC_REFERENCE,
2234 REPL_TYPE_NUMERIC_REFERENCE,
2235 REPL_TYPE_CHANGE_CASE
2240 CHANGE_CASE_NONE = 1 << 0,
2241 CHANGE_CASE_UPPER = 1 << 1,
2242 CHANGE_CASE_LOWER = 1 << 2,
2243 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
2244 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
2245 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
2246 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
2247 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
2250 struct _InterpolationData
2256 ChangeCase change_case;
2260 free_interpolation_data (InterpolationData *data)
2262 g_free (data->text);
2266 static const gchar *
2267 expand_escape (const gchar *replacement,
2269 InterpolationData *data,
2274 const gchar *error_detail;
2276 GError *tmp_error = NULL;
2284 data->type = REPL_TYPE_CHARACTER;
2289 data->type = REPL_TYPE_CHARACTER;
2294 data->type = REPL_TYPE_CHARACTER;
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;
2329 h = g_ascii_xdigit_value (*p);
2332 error_detail = _("hexadecimal digit or '}' expected");
2343 for (i = 0; i < 2; i++)
2345 h = g_ascii_xdigit_value (*p);
2348 error_detail = _("hexadecimal digit expected");
2355 data->type = REPL_TYPE_STRING;
2356 data->text = g_new0 (gchar, 8);
2357 g_unichar_to_utf8 (x, data->text);
2361 data->type = REPL_TYPE_CHANGE_CASE;
2362 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2366 data->type = REPL_TYPE_CHANGE_CASE;
2367 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2371 data->type = REPL_TYPE_CHANGE_CASE;
2372 data->change_case = CHANGE_CASE_LOWER;
2376 data->type = REPL_TYPE_CHANGE_CASE;
2377 data->change_case = CHANGE_CASE_UPPER;
2381 data->type = REPL_TYPE_CHANGE_CASE;
2382 data->change_case = CHANGE_CASE_NONE;
2388 error_detail = _("missing '<' in symbolic reference");
2397 error_detail = _("unfinished symbolic reference");
2404 error_detail = _("zero-length symbolic reference");
2407 if (g_ascii_isdigit (*q))
2412 h = g_ascii_digit_value (*q);
2415 error_detail = _("digit expected");
2424 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2431 if (!g_ascii_isalnum (*r))
2433 error_detail = _("illegal symbolic reference");
2440 data->text = g_strndup (q, p - q);
2441 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2446 /* if \0 is followed by a number is an octal number representing a
2447 * character, else it is a numeric reference. */
2448 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2451 p = g_utf8_next_char (p);
2464 for (i = 0; i < 3; i++)
2466 h = g_ascii_digit_value (*p);
2476 if (i == 2 && base == 10)
2482 if (base == 8 || i == 3)
2484 data->type = REPL_TYPE_STRING;
2485 data->text = g_new0 (gchar, 8);
2486 g_unichar_to_utf8 (x, data->text);
2490 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2495 error_detail = _("stray final '\\'");
2499 error_detail = _("unknown escape sequence");
2506 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2507 tmp_error = g_error_new (G_REGEX_ERROR,
2508 G_REGEX_ERROR_REPLACE,
2509 _("Error while parsing replacement "
2510 "text \"%s\" at char %lu: %s"),
2512 (gulong)(p - replacement),
2514 g_propagate_error (error, tmp_error);
2520 split_replacement (const gchar *replacement,
2524 InterpolationData *data;
2525 const gchar *p, *start;
2527 start = p = replacement;
2532 data = g_new0 (InterpolationData, 1);
2533 start = p = expand_escape (replacement, p, data, error);
2536 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2537 free_interpolation_data (data);
2541 list = g_list_prepend (list, data);
2546 if (*p == '\\' || *p == '\0')
2550 data = g_new0 (InterpolationData, 1);
2551 data->text = g_strndup (start, p - start);
2552 data->type = REPL_TYPE_STRING;
2553 list = g_list_prepend (list, data);
2559 return g_list_reverse (list);
2562 /* Change the case of c based on change_case. */
2563 #define CHANGE_CASE(c, change_case) \
2564 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2565 g_unichar_tolower (c) : \
2566 g_unichar_toupper (c))
2569 string_append (GString *string,
2571 ChangeCase *change_case)
2575 if (text[0] == '\0')
2578 if (*change_case == CHANGE_CASE_NONE)
2580 g_string_append (string, text);
2582 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2584 c = g_utf8_get_char (text);
2585 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2586 g_string_append (string, g_utf8_next_char (text));
2587 *change_case = CHANGE_CASE_NONE;
2591 while (*text != '\0')
2593 c = g_utf8_get_char (text);
2594 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2595 text = g_utf8_next_char (text);
2601 interpolate_replacement (const GMatchInfo *match_info,
2606 InterpolationData *idata;
2608 ChangeCase change_case = CHANGE_CASE_NONE;
2610 for (list = data; list; list = list->next)
2613 switch (idata->type)
2615 case REPL_TYPE_STRING:
2616 string_append (result, idata->text, &change_case);
2618 case REPL_TYPE_CHARACTER:
2619 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2620 if (change_case & CHANGE_CASE_SINGLE_MASK)
2621 change_case = CHANGE_CASE_NONE;
2623 case REPL_TYPE_NUMERIC_REFERENCE:
2624 match = g_match_info_fetch (match_info, idata->num);
2627 string_append (result, match, &change_case);
2631 case REPL_TYPE_SYMBOLIC_REFERENCE:
2632 match = g_match_info_fetch_named (match_info, idata->text);
2635 string_append (result, match, &change_case);
2639 case REPL_TYPE_CHANGE_CASE:
2640 change_case = idata->change_case;
2648 /* whether actual match_info is needed for replacement, i.e.
2649 * whether there are references
2652 interpolation_list_needs_match (GList *list)
2654 while (list != NULL)
2656 InterpolationData *data = list->data;
2658 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2659 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2672 * @regex: a #GRegex structure
2673 * @string: (array length=string_len): the string to perform matches against
2674 * @string_len: the length of @string, or -1 if @string is nul-terminated
2675 * @start_position: starting index of the string to match
2676 * @replacement: text to replace each match with
2677 * @match_options: options for the match
2678 * @error: location to store the error occurring, or %NULL to ignore errors
2680 * Replaces all occurrences of the pattern in @regex with the
2681 * replacement text. Backreferences of the form '\number' or
2682 * '\g<number>' in the replacement text are interpolated by the
2683 * number-th captured subexpression of the match, '\g<name>' refers
2684 * to the captured subexpression with the given name. '\0' refers to the
2685 * complete match, but '\0' followed by a number is the octal representation
2686 * of a character. To include a literal '\' in the replacement, write '\\'.
2687 * There are also escapes that changes the case of the following text:
2690 * <varlistentry><term>\l</term>
2692 * <para>Convert to lower case the next character</para>
2695 * <varlistentry><term>\u</term>
2697 * <para>Convert to upper case the next character</para>
2700 * <varlistentry><term>\L</term>
2702 * <para>Convert to lower case till \E</para>
2705 * <varlistentry><term>\U</term>
2707 * <para>Convert to upper case till \E</para>
2710 * <varlistentry><term>\E</term>
2712 * <para>End case modification</para>
2717 * If you do not need to use backreferences use g_regex_replace_literal().
2719 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2720 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2721 * you can use g_regex_replace_literal().
2723 * Setting @start_position differs from just passing over a shortened
2724 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2725 * begins with any kind of lookbehind assertion, such as "\b".
2727 * Returns: a newly allocated string containing the replacements
2732 g_regex_replace (const GRegex *regex,
2733 const gchar *string,
2735 gint start_position,
2736 const gchar *replacement,
2737 GRegexMatchFlags match_options,
2742 GError *tmp_error = NULL;
2744 g_return_val_if_fail (regex != NULL, NULL);
2745 g_return_val_if_fail (string != NULL, NULL);
2746 g_return_val_if_fail (start_position >= 0, NULL);
2747 g_return_val_if_fail (replacement != NULL, NULL);
2748 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2749 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2751 list = split_replacement (replacement, &tmp_error);
2752 if (tmp_error != NULL)
2754 g_propagate_error (error, tmp_error);
2758 result = g_regex_replace_eval (regex,
2759 string, string_len, start_position,
2761 interpolate_replacement,
2764 if (tmp_error != NULL)
2765 g_propagate_error (error, tmp_error);
2767 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2773 literal_replacement (const GMatchInfo *match_info,
2777 g_string_append (result, data);
2782 * g_regex_replace_literal:
2783 * @regex: a #GRegex structure
2784 * @string: (array length=string_len): the string to perform matches against
2785 * @string_len: the length of @string, or -1 if @string is nul-terminated
2786 * @start_position: starting index of the string to match
2787 * @replacement: text to replace each match with
2788 * @match_options: options for the match
2789 * @error: location to store the error occurring, or %NULL to ignore errors
2791 * Replaces all occurrences of the pattern in @regex with the
2792 * replacement text. @replacement is replaced literally, to
2793 * include backreferences use g_regex_replace().
2795 * Setting @start_position differs from just passing over a
2796 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2797 * case of a pattern that begins with any kind of lookbehind
2798 * assertion, such as "\b".
2800 * Returns: a newly allocated string containing the replacements
2805 g_regex_replace_literal (const GRegex *regex,
2806 const gchar *string,
2808 gint start_position,
2809 const gchar *replacement,
2810 GRegexMatchFlags match_options,
2813 g_return_val_if_fail (replacement != NULL, NULL);
2814 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2816 return g_regex_replace_eval (regex,
2817 string, string_len, start_position,
2819 literal_replacement,
2820 (gpointer)replacement,
2825 * g_regex_replace_eval:
2826 * @regex: a #GRegex structure from g_regex_new()
2827 * @string: (array length=string_len): string to perform matches against
2828 * @string_len: the length of @string, or -1 if @string is nul-terminated
2829 * @start_position: starting index of the string to match
2830 * @match_options: options for the match
2831 * @eval: a function to call for each match
2832 * @user_data: user data to pass to the function
2833 * @error: location to store the error occurring, or %NULL to ignore errors
2835 * Replaces occurrences of the pattern in regex with the output of
2836 * @eval for that occurrence.
2838 * Setting @start_position differs from just passing over a shortened
2839 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2840 * that begins with any kind of lookbehind assertion, such as "\b".
2842 * The following example uses g_regex_replace_eval() to replace multiple
2846 * eval_cb (const GMatchInfo *info,
2853 * match = g_match_info_fetch (info, 0);
2854 * r = g_hash_table_lookup ((GHashTable *)data, match);
2855 * g_string_append (res, r);
2867 * h = g_hash_table_new (g_str_hash, g_str_equal);
2869 * g_hash_table_insert (h, "1", "ONE");
2870 * g_hash_table_insert (h, "2", "TWO");
2871 * g_hash_table_insert (h, "3", "THREE");
2872 * g_hash_table_insert (h, "4", "FOUR");
2874 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2875 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2876 * g_hash_table_destroy (h);
2881 * Returns: a newly allocated string containing the replacements
2886 g_regex_replace_eval (const GRegex *regex,
2887 const gchar *string,
2889 gint start_position,
2890 GRegexMatchFlags match_options,
2891 GRegexEvalCallback eval,
2895 GMatchInfo *match_info;
2898 gboolean done = FALSE;
2899 GError *tmp_error = NULL;
2901 g_return_val_if_fail (regex != NULL, NULL);
2902 g_return_val_if_fail (string != NULL, NULL);
2903 g_return_val_if_fail (start_position >= 0, NULL);
2904 g_return_val_if_fail (eval != NULL, NULL);
2905 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2908 string_len = strlen (string);
2910 result = g_string_sized_new (string_len);
2912 /* run down the string making matches. */
2913 g_regex_match_full (regex, string, string_len, start_position,
2914 match_options, &match_info, &tmp_error);
2915 while (!done && g_match_info_matches (match_info))
2917 g_string_append_len (result,
2919 match_info->offsets[0] - str_pos);
2920 done = (*eval) (match_info, result, user_data);
2921 str_pos = match_info->offsets[1];
2922 g_match_info_next (match_info, &tmp_error);
2924 g_match_info_free (match_info);
2925 if (tmp_error != NULL)
2927 g_propagate_error (error, tmp_error);
2928 g_string_free (result, TRUE);
2932 g_string_append_len (result, string + str_pos, string_len - str_pos);
2933 return g_string_free (result, FALSE);
2937 * g_regex_check_replacement:
2938 * @replacement: the replacement string
2939 * @has_references: (out) (allow-none): location to store information about
2940 * references in @replacement or %NULL
2941 * @error: location to store error
2943 * Checks whether @replacement is a valid replacement string
2944 * (see g_regex_replace()), i.e. that all escape sequences in
2947 * If @has_references is not %NULL then @replacement is checked
2948 * for pattern references. For instance, replacement text 'foo\n'
2949 * does not contain references and may be evaluated without information
2950 * about actual match, but '\0\1' (whole match followed by first
2951 * subpattern) requires valid #GMatchInfo object.
2953 * Returns: whether @replacement is a valid replacement string
2958 g_regex_check_replacement (const gchar *replacement,
2959 gboolean *has_references,
2965 list = split_replacement (replacement, &tmp);
2969 g_propagate_error (error, tmp);
2974 *has_references = interpolation_list_needs_match (list);
2976 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2982 * g_regex_escape_nul:
2983 * @string: the string to escape
2984 * @length: the length of @string
2986 * Escapes the nul characters in @string to "\x00". It can be used
2987 * to compile a regex with embedded nul characters.
2989 * For completeness, @length can be -1 for a nul-terminated string.
2990 * In this case the output string will be of course equal to @string.
2992 * Returns: a newly-allocated escaped string
2997 g_regex_escape_nul (const gchar *string,
3001 const gchar *p, *piece_start, *end;
3004 g_return_val_if_fail (string != NULL, NULL);
3007 return g_strdup (string);
3009 end = string + length;
3010 p = piece_start = string;
3011 escaped = g_string_sized_new (length + 1);
3019 if (p != piece_start)
3021 /* copy the previous piece. */
3022 g_string_append_len (escaped, piece_start, p - piece_start);
3024 if ((backslashes & 1) == 0)
3025 g_string_append_c (escaped, '\\');
3026 g_string_append_c (escaped, 'x');
3027 g_string_append_c (escaped, '0');
3028 g_string_append_c (escaped, '0');
3038 p = g_utf8_next_char (p);
3043 if (piece_start < end)
3044 g_string_append_len (escaped, piece_start, end - piece_start);
3046 return g_string_free (escaped, FALSE);
3050 * g_regex_escape_string:
3051 * @string: (array length=length): the string to escape
3052 * @length: the length of @string, or -1 if @string is nul-terminated
3054 * Escapes the special characters used for regular expressions
3055 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
3056 * function is useful to dynamically generate regular expressions.
3058 * @string can contain nul characters that are replaced with "\0",
3059 * in this case remember to specify the correct length of @string
3062 * Returns: a newly-allocated escaped string
3067 g_regex_escape_string (const gchar *string,
3071 const char *p, *piece_start, *end;
3073 g_return_val_if_fail (string != NULL, NULL);
3076 length = strlen (string);
3078 end = string + length;
3079 p = piece_start = string;
3080 escaped = g_string_sized_new (length + 1);
3101 if (p != piece_start)
3102 /* copy the previous piece. */
3103 g_string_append_len (escaped, piece_start, p - piece_start);
3104 g_string_append_c (escaped, '\\');
3106 g_string_append_c (escaped, '0');
3108 g_string_append_c (escaped, *p);
3112 p = g_utf8_next_char (p);
3117 if (piece_start < end)
3118 g_string_append_len (escaped, piece_start, end - piece_start);
3120 return g_string_free (escaped, FALSE);