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)
151 /* we rely on these flags having the same values */
152 G_STATIC_ASSERT (G_REGEX_CASELESS == PCRE_CASELESS);
153 G_STATIC_ASSERT (G_REGEX_MULTILINE == PCRE_MULTILINE);
154 G_STATIC_ASSERT (G_REGEX_DOTALL == PCRE_DOTALL);
155 G_STATIC_ASSERT (G_REGEX_EXTENDED == PCRE_EXTENDED);
156 G_STATIC_ASSERT (G_REGEX_ANCHORED == PCRE_ANCHORED);
157 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY == PCRE_DOLLAR_ENDONLY);
158 G_STATIC_ASSERT (G_REGEX_UNGREEDY == PCRE_UNGREEDY);
159 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE == PCRE_NO_AUTO_CAPTURE);
160 G_STATIC_ASSERT (G_REGEX_DUPNAMES == PCRE_DUPNAMES);
161 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR == PCRE_NEWLINE_CR);
162 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF == PCRE_NEWLINE_LF);
163 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
164 G_STATIC_ASSERT (G_REGEX_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
165 G_STATIC_ASSERT (G_REGEX_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
166 G_STATIC_ASSERT (G_REGEX_JAVASCRIPT_COMPAT == PCRE_JAVASCRIPT_COMPAT);
168 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED == PCRE_ANCHORED);
169 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL == PCRE_NOTBOL);
170 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL == PCRE_NOTEOL);
171 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY == PCRE_NOTEMPTY);
172 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL == PCRE_PARTIAL);
173 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR == PCRE_NEWLINE_CR);
174 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF == PCRE_NEWLINE_LF);
175 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
176 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY == PCRE_NEWLINE_ANY);
177 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
178 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
179 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANY == PCRE_BSR_UNICODE);
181 /* These PCRE flags are unused or not exposed publically in GRegexFlags, so
182 * it should be ok to reuse them for different things.
184 G_STATIC_ASSERT (G_REGEX_OPTIMIZE == PCRE_NO_UTF8_CHECK);
185 G_STATIC_ASSERT (G_REGEX_RAW == PCRE_UTF8);
187 /* if the string is in UTF-8 use g_utf8_ functions, else use
189 #define NEXT_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
191 g_utf8_next_char (s))
192 #define PREV_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
194 g_utf8_prev_char (s))
198 volatile gint ref_count; /* the ref count */
199 GRegex *regex; /* the regex */
200 GRegexMatchFlags match_opts; /* options used at match time on the regex */
201 gint matches; /* number of matching sub patterns */
202 gint pos; /* position in the string where last match left off */
203 gint n_offsets; /* number of offsets */
204 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
205 gint *workspace; /* workspace for pcre_dfa_exec() */
206 gint n_workspace; /* number of workspace elements */
207 const gchar *string; /* string passed to the match function */
208 gssize string_len; /* length of string */
213 volatile gint ref_count; /* the ref count for the immutable part */
214 gchar *pattern; /* the pattern */
215 pcre *pcre_re; /* compiled form of the pattern */
216 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
217 GRegexMatchFlags match_opts; /* options used at match time on the regex */
218 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
221 /* TRUE if ret is an error code, FALSE otherwise. */
222 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
224 typedef struct _InterpolationData InterpolationData;
225 static gboolean interpolation_list_needs_match (GList *list);
226 static gboolean interpolate_replacement (const GMatchInfo *match_info,
229 static GList *split_replacement (const gchar *replacement,
231 static void free_interpolation_data (InterpolationData *data);
235 match_error (gint errcode)
239 case PCRE_ERROR_NOMATCH:
242 case PCRE_ERROR_NULL:
243 /* NULL argument, this should not happen in GRegex */
244 g_warning ("A NULL argument was passed to PCRE");
246 case PCRE_ERROR_BADOPTION:
247 return "bad options";
248 case PCRE_ERROR_BADMAGIC:
249 return _("corrupted object");
250 case PCRE_ERROR_UNKNOWN_OPCODE:
251 return N_("internal error or corrupted object");
252 case PCRE_ERROR_NOMEMORY:
253 return _("out of memory");
254 case PCRE_ERROR_NOSUBSTRING:
255 /* not used by pcre_exec() */
257 case PCRE_ERROR_MATCHLIMIT:
258 return _("backtracking limit reached");
259 case PCRE_ERROR_CALLOUT:
260 /* callouts are not implemented */
262 case PCRE_ERROR_BADUTF8:
263 case PCRE_ERROR_BADUTF8_OFFSET:
264 /* we do not check if strings are valid */
266 case PCRE_ERROR_PARTIAL:
269 case PCRE_ERROR_BADPARTIAL:
270 return _("the pattern contains items not supported for partial matching");
271 case PCRE_ERROR_INTERNAL:
272 return _("internal error");
273 case PCRE_ERROR_BADCOUNT:
274 /* negative ovecsize, this should not happen in GRegex */
275 g_warning ("A negative ovecsize was passed to PCRE");
277 case PCRE_ERROR_DFA_UITEM:
278 return _("the pattern contains items not supported for partial matching");
279 case PCRE_ERROR_DFA_UCOND:
280 return _("back references as conditions are not supported for partial matching");
281 case PCRE_ERROR_DFA_UMLIMIT:
282 /* the match_field field is not used in GRegex */
284 case PCRE_ERROR_DFA_WSSIZE:
285 /* handled expanding the workspace */
287 case PCRE_ERROR_DFA_RECURSE:
288 case PCRE_ERROR_RECURSIONLIMIT:
289 return _("recursion limit reached");
290 case PCRE_ERROR_BADNEWLINE:
291 return _("invalid combination of newline flags");
292 case PCRE_ERROR_BADOFFSET:
293 return _("bad offset");
294 case PCRE_ERROR_SHORTUTF8:
295 return _("short utf8");
296 case PCRE_ERROR_RECURSELOOP:
297 return _("recursion loop");
301 return _("unknown error");
305 translate_compile_error (gint *errcode, const gchar **errmsg)
307 /* Compile errors are created adding 100 to the error code returned
309 * If errcode is known we put the translatable error message in
310 * erromsg. If errcode is unknown we put the generic
311 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
312 * untranslated error message returned by PCRE.
313 * Note that there can be more PCRE errors with the same GRegexError
314 * and that some PCRE errors are useless for us.
320 case G_REGEX_ERROR_STRAY_BACKSLASH:
321 *errmsg = _("\\ at end of pattern");
323 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
324 *errmsg = _("\\c at end of pattern");
326 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
327 *errmsg = _("unrecognized character follows \\");
329 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
330 *errmsg = _("numbers out of order in {} quantifier");
332 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
333 *errmsg = _("number too big in {} quantifier");
335 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
336 *errmsg = _("missing terminating ] for character class");
338 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
339 *errmsg = _("invalid escape sequence in character class");
341 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
342 *errmsg = _("range out of order in character class");
344 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
345 *errmsg = _("nothing to repeat");
347 case 111: /* internal error: unexpected repeat */
348 *errcode = G_REGEX_ERROR_INTERNAL;
349 *errmsg = _("unexpected repeat");
351 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
352 *errmsg = _("unrecognized character after (? or (?-");
354 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
355 *errmsg = _("POSIX named classes are supported only within a class");
357 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
358 *errmsg = _("missing terminating )");
360 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
361 *errmsg = _("reference to non-existent subpattern");
363 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
364 *errmsg = _("missing ) after comment");
366 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
367 *errmsg = _("regular expression is too large");
369 case G_REGEX_ERROR_MEMORY_ERROR:
370 *errmsg = _("failed to get memory");
372 case 122: /* unmatched parentheses */
373 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
374 *errmsg = _(") without opening (");
376 case 123: /* internal error: code overflow */
377 *errcode = G_REGEX_ERROR_INTERNAL;
378 *errmsg = _("code overflow");
380 case 124: /* "unrecognized character after (?<\0 */
381 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
382 *errmsg = _("unrecognized character after (?<");
384 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
385 *errmsg = _("lookbehind assertion is not fixed length");
387 case G_REGEX_ERROR_MALFORMED_CONDITION:
388 *errmsg = _("malformed number or name after (?(");
390 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
391 *errmsg = _("conditional group contains more than two branches");
393 case G_REGEX_ERROR_ASSERTION_EXPECTED:
394 *errmsg = _("assertion expected after (?(");
397 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
398 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
399 * sequences here, '(?-54' would be an example for the second group.
401 *errmsg = _("(?R or (?[+-]digits must be followed by )");
403 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
404 *errmsg = _("unknown POSIX class name");
406 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
407 *errmsg = _("POSIX collating elements are not supported");
409 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
410 *errmsg = _("character value in \\x{...} sequence is too large");
412 case G_REGEX_ERROR_INVALID_CONDITION:
413 *errmsg = _("invalid condition (?(0)");
415 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
416 *errmsg = _("\\C not allowed in lookbehind assertion");
418 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
419 /* A number of Perl escapes are not handled by PCRE.
420 * Therefore it explicitly raises ERR37.
422 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
423 *errmsg = _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
425 case G_REGEX_ERROR_INFINITE_LOOP:
426 *errmsg = _("recursive call could loop indefinitely");
428 case 141: /* unrecognized character after (?P\0 */
429 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
430 *errmsg = _("unrecognized character after (?P");
432 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
433 *errmsg = _("missing terminator in subpattern name");
435 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
436 *errmsg = _("two named subpatterns have the same name");
438 case G_REGEX_ERROR_MALFORMED_PROPERTY:
439 *errmsg = _("malformed \\P or \\p sequence");
441 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
442 *errmsg = _("unknown property name after \\P or \\p");
444 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
445 *errmsg = _("subpattern name is too long (maximum 32 characters)");
447 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
448 *errmsg = _("too many named subpatterns (maximum 10,000)");
450 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
451 *errmsg = _("octal value is greater than \\377");
453 case 152: /* internal error: overran compiling workspace */
454 *errcode = G_REGEX_ERROR_INTERNAL;
455 *errmsg = _("overran compiling workspace");
457 case 153: /* internal error: previously-checked referenced subpattern not found */
458 *errcode = G_REGEX_ERROR_INTERNAL;
459 *errmsg = _("previously-checked referenced subpattern not found");
461 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
462 *errmsg = _("DEFINE group contains more than one branch");
464 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
465 *errmsg = _("inconsistent NEWLINE options");
467 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
468 *errmsg = _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
469 "number, or by a plain number");
471 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE:
472 *errmsg = _("a numbered reference must not be zero");
474 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
475 *errmsg = _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
477 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB:
478 *errmsg = _("(*VERB) not recognized");
480 case G_REGEX_ERROR_NUMBER_TOO_BIG:
481 *errmsg = _("number is too bug");
483 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME:
484 *errmsg = _("missing subpattern name after (?&");
486 case G_REGEX_ERROR_MISSING_DIGIT:
487 *errmsg = _("digit expected after (?+");
489 case G_REGEX_ERROR_INVALID_DATA_CHARACTER:
490 *errmsg = _("] is an invalid data character in JavaScript compatibility mode");
492 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME:
493 *errmsg = _("different names for subpatterns of the same number are not allowed");
495 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
496 *errmsg = _("(*MARK) must have an argument");
498 case G_REGEX_ERROR_INVALID_CONTROL_CHAR:
499 *errmsg = _( "\\c must be followed by an ASCII character");
501 case G_REGEX_ERROR_MISSING_NAME:
502 *errmsg = _("\\k is not followed by a braced, angle-bracketed, or quoted name");
504 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS:
505 *errmsg = _("\\N is not supported in a class");
507 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES:
508 *errmsg = _("too many forward references");
510 case G_REGEX_ERROR_NAME_TOO_LONG:
511 *errmsg = _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
514 case 116: /* erroffset passed as NULL */
515 /* This should not happen as we never pass a NULL erroffset */
516 g_warning ("erroffset passed as NULL");
517 *errcode = G_REGEX_ERROR_COMPILE;
519 case 117: /* unknown option bit(s) set */
520 /* This should not happen as we check options before passing them
521 * to pcre_compile2() */
522 g_warning ("unknown option bit(s) set");
523 *errcode = G_REGEX_ERROR_COMPILE;
525 case 132: /* this version of PCRE is compiled without UTF support */
526 case 144: /* invalid UTF-8 string */
527 case 145: /* support for \\P, \\p, and \\X has not been compiled */
528 case 167: /* this version of PCRE is not compiled with Unicode property support */
529 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
530 case 174: /* invalid UTF-16 string */
531 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
532 * and we do not check if strings are valid */
533 case 170: /* internal error: unknown opcode in find_fixedlength() */
534 *errcode = G_REGEX_ERROR_INTERNAL;
538 *errcode = G_REGEX_ERROR_COMPILE;
545 match_info_new (const GRegex *regex,
552 GMatchInfo *match_info;
555 string_len = strlen (string);
557 match_info = g_new0 (GMatchInfo, 1);
558 match_info->ref_count = 1;
559 match_info->regex = g_regex_ref ((GRegex *)regex);
560 match_info->string = string;
561 match_info->string_len = string_len;
562 match_info->matches = PCRE_ERROR_NOMATCH;
563 match_info->pos = start_position;
564 match_info->match_opts = match_options;
568 /* These values should be enough for most cases, if they are not
569 * enough g_regex_match_all_full() will expand them. */
570 match_info->n_offsets = 24;
571 match_info->n_workspace = 100;
572 match_info->workspace = g_new (gint, match_info->n_workspace);
577 pcre_fullinfo (regex->pcre_re, regex->extra,
578 PCRE_INFO_CAPTURECOUNT, &capture_count);
579 match_info->n_offsets = (capture_count + 1) * 3;
582 match_info->offsets = g_new0 (gint, match_info->n_offsets);
583 /* Set an invalid position for the previous match. */
584 match_info->offsets[0] = -1;
585 match_info->offsets[1] = -1;
591 * g_match_info_get_regex:
592 * @match_info: a #GMatchInfo
594 * Returns #GRegex object used in @match_info. It belongs to Glib
595 * and must not be freed. Use g_regex_ref() if you need to keep it
596 * after you free @match_info object.
598 * Returns: #GRegex object used in @match_info
603 g_match_info_get_regex (const GMatchInfo *match_info)
605 g_return_val_if_fail (match_info != NULL, NULL);
606 return match_info->regex;
610 * g_match_info_get_string:
611 * @match_info: a #GMatchInfo
613 * Returns the string searched with @match_info. This is the
614 * string passed to g_regex_match() or g_regex_replace() so
615 * you may not free it before calling this function.
617 * Returns: the string searched with @match_info
622 g_match_info_get_string (const GMatchInfo *match_info)
624 g_return_val_if_fail (match_info != NULL, NULL);
625 return match_info->string;
630 * @match_info: a #GMatchInfo
632 * Increases reference count of @match_info by 1.
634 * Returns: @match_info
639 g_match_info_ref (GMatchInfo *match_info)
641 g_return_val_if_fail (match_info != NULL, NULL);
642 g_atomic_int_inc (&match_info->ref_count);
647 * g_match_info_unref:
648 * @match_info: a #GMatchInfo
650 * Decreases reference count of @match_info by 1. When reference count drops
651 * to zero, it frees all the memory associated with the match_info structure.
656 g_match_info_unref (GMatchInfo *match_info)
658 if (g_atomic_int_dec_and_test (&match_info->ref_count))
660 g_regex_unref (match_info->regex);
661 g_free (match_info->offsets);
662 g_free (match_info->workspace);
669 * @match_info: (allow-none): a #GMatchInfo, or %NULL
671 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
677 g_match_info_free (GMatchInfo *match_info)
679 if (match_info == NULL)
682 g_match_info_unref (match_info);
687 * @match_info: a #GMatchInfo structure
688 * @error: location to store the error occurring, or %NULL to ignore errors
690 * Scans for the next match using the same parameters of the previous
691 * call to g_regex_match_full() or g_regex_match() that returned
694 * The match is done on the string passed to the match function, so you
695 * cannot free it before calling this function.
697 * Returns: %TRUE is the string matched, %FALSE otherwise
702 g_match_info_next (GMatchInfo *match_info,
705 gint prev_match_start;
708 g_return_val_if_fail (match_info != NULL, FALSE);
709 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
710 g_return_val_if_fail (match_info->pos >= 0, FALSE);
712 prev_match_start = match_info->offsets[0];
713 prev_match_end = match_info->offsets[1];
715 if (match_info->pos > match_info->string_len)
717 /* we have reached the end of the string */
718 match_info->pos = -1;
719 match_info->matches = PCRE_ERROR_NOMATCH;
723 match_info->matches = pcre_exec (match_info->regex->pcre_re,
724 match_info->regex->extra,
726 match_info->string_len,
728 match_info->regex->match_opts | match_info->match_opts,
730 match_info->n_offsets);
731 if (IS_PCRE_ERROR (match_info->matches))
733 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
734 _("Error while matching regular expression %s: %s"),
735 match_info->regex->pattern, match_error (match_info->matches));
739 /* avoid infinite loops if the pattern is an empty string or something
741 if (match_info->pos == match_info->offsets[1])
743 if (match_info->pos > match_info->string_len)
745 /* we have reached the end of the string */
746 match_info->pos = -1;
747 match_info->matches = PCRE_ERROR_NOMATCH;
751 match_info->pos = NEXT_CHAR (match_info->regex,
752 &match_info->string[match_info->pos]) -
757 match_info->pos = match_info->offsets[1];
760 /* it's possible to get two identical matches when we are matching
761 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
762 * the string is "RegExTest" we have:
763 * - search at position 0: match from 0 to 0
764 * - search at position 1: match from 3 to 3
765 * - search at position 3: match from 3 to 3 (duplicate)
766 * - search at position 4: match from 5 to 5
767 * - search at position 5: match from 5 to 5 (duplicate)
768 * - search at position 6: no match -> stop
769 * so we have to ignore the duplicates.
770 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
771 if (match_info->matches >= 0 &&
772 prev_match_start == match_info->offsets[0] &&
773 prev_match_end == match_info->offsets[1])
775 /* ignore this match and search the next one */
776 return g_match_info_next (match_info, error);
779 return match_info->matches >= 0;
783 * g_match_info_matches:
784 * @match_info: a #GMatchInfo structure
786 * Returns whether the previous match operation succeeded.
788 * Returns: %TRUE if the previous match operation succeeded,
794 g_match_info_matches (const GMatchInfo *match_info)
796 g_return_val_if_fail (match_info != NULL, FALSE);
798 return match_info->matches >= 0;
802 * g_match_info_get_match_count:
803 * @match_info: a #GMatchInfo structure
805 * Retrieves the number of matched substrings (including substring 0,
806 * that is the whole matched text), so 1 is returned if the pattern
807 * has no substrings in it and 0 is returned if the match failed.
809 * If the last match was obtained using the DFA algorithm, that is
810 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
811 * count is not that of the number of capturing parentheses but that of
812 * the number of matched substrings.
814 * Returns: Number of matched substrings, or -1 if an error occurred
819 g_match_info_get_match_count (const GMatchInfo *match_info)
821 g_return_val_if_fail (match_info, -1);
823 if (match_info->matches == PCRE_ERROR_NOMATCH)
826 else if (match_info->matches < PCRE_ERROR_NOMATCH)
831 return match_info->matches;
835 * g_match_info_is_partial_match:
836 * @match_info: a #GMatchInfo structure
838 * Usually if the string passed to g_regex_match*() matches as far as
839 * it goes, but is too short to match the entire pattern, %FALSE is
840 * returned. There are circumstances where it might be helpful to
841 * distinguish this case from other cases in which there is no match.
843 * Consider, for example, an application where a human is required to
844 * type in data for a field with specific formatting requirements. An
845 * example might be a date in the form ddmmmyy, defined by the pattern
846 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
847 * If the application sees the user’s keystrokes one by one, and can
848 * check that what has been typed so far is potentially valid, it is
849 * able to raise an error as soon as a mistake is made.
851 * GRegex supports the concept of partial matching by means of the
852 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
853 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
854 * for a complete match, %FALSE otherwise. But, when these functions
855 * return %FALSE, you can check if the match was partial calling
856 * g_match_info_is_partial_match().
858 * When using partial matching you cannot use g_match_info_fetch*().
860 * Because of the way certain internal optimizations are implemented
861 * the partial matching algorithm cannot be used with all patterns.
862 * So repeated single characters such as "a{2,4}" and repeated single
863 * meta-sequences such as "\d+" are not permitted if the maximum number
864 * of occurrences is greater than one. Optional items such as "\d?"
865 * (where the maximum is one) are permitted. Quantifiers with any values
866 * are permitted after parentheses, so the invalid examples above can be
867 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
868 * for a pattern that does not conform to the restrictions, matching
869 * functions return an error.
871 * Returns: %TRUE if the match was partial, %FALSE otherwise
876 g_match_info_is_partial_match (const GMatchInfo *match_info)
878 g_return_val_if_fail (match_info != NULL, FALSE);
880 return match_info->matches == PCRE_ERROR_PARTIAL;
884 * g_match_info_expand_references:
885 * @match_info: (allow-none): a #GMatchInfo or %NULL
886 * @string_to_expand: the string to expand
887 * @error: location to store the error occurring, or %NULL to ignore errors
889 * Returns a new string containing the text in @string_to_expand with
890 * references and escape sequences expanded. References refer to the last
891 * match done with @string against @regex and have the same syntax used by
894 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
895 * passed to g_regex_new().
897 * The backreferences are extracted from the string passed to the match
898 * function, so you cannot call this function after freeing the string.
900 * @match_info may be %NULL in which case @string_to_expand must not
901 * contain references. For instance "foo\n" does not refer to an actual
902 * pattern and '\n' merely will be replaced with \n character,
903 * while to expand "\0" (whole match) one needs the result of a match.
904 * Use g_regex_check_replacement() to find out whether @string_to_expand
905 * contains references.
907 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
912 g_match_info_expand_references (const GMatchInfo *match_info,
913 const gchar *string_to_expand,
918 GError *tmp_error = NULL;
920 g_return_val_if_fail (string_to_expand != NULL, NULL);
921 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
923 list = split_replacement (string_to_expand, &tmp_error);
924 if (tmp_error != NULL)
926 g_propagate_error (error, tmp_error);
930 if (!match_info && interpolation_list_needs_match (list))
932 g_critical ("String '%s' contains references to the match, can't "
933 "expand references without GMatchInfo object",
938 result = g_string_sized_new (strlen (string_to_expand));
939 interpolate_replacement (match_info, result, list);
941 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
943 return g_string_free (result, FALSE);
947 * g_match_info_fetch:
948 * @match_info: #GMatchInfo structure
949 * @match_num: number of the sub expression
951 * Retrieves the text matching the @match_num<!-- -->'th capturing
952 * parentheses. 0 is the full text of the match, 1 is the first paren
953 * set, 2 the second, and so on.
955 * If @match_num is a valid sub pattern but it didn't match anything
956 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
957 * string is returned.
959 * If the match was obtained using the DFA algorithm, that is using
960 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
961 * string is not that of a set of parentheses but that of a matched
962 * substring. Substrings are matched in reverse order of length, so
963 * 0 is the longest match.
965 * The string is fetched from the string passed to the match function,
966 * so you cannot call this function after freeing the string.
968 * Returns: (allow-none): The matched substring, or %NULL if an error
969 * occurred. You have to free the string yourself
974 g_match_info_fetch (const GMatchInfo *match_info,
977 /* we cannot use pcre_get_substring() because it allocates the
978 * string using pcre_malloc(). */
982 g_return_val_if_fail (match_info != NULL, NULL);
983 g_return_val_if_fail (match_num >= 0, NULL);
985 /* match_num does not exist or it didn't matched, i.e. matching "b"
986 * against "(a)?b" then group 0 is empty. */
987 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
989 else if (start == -1)
990 match = g_strdup ("");
992 match = g_strndup (&match_info->string[start], end - start);
998 * g_match_info_fetch_pos:
999 * @match_info: #GMatchInfo structure
1000 * @match_num: number of the sub expression
1001 * @start_pos: (out) (allow-none): pointer to location where to store
1002 * the start position, or %NULL
1003 * @end_pos: (out) (allow-none): pointer to location where to store
1004 * the end position, or %NULL
1006 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
1007 * parentheses. 0 is the full text of the match, 1 is the first
1008 * paren set, 2 the second, and so on.
1010 * If @match_num is a valid sub pattern but it didn't match anything
1011 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
1012 * and @end_pos are set to -1 and %TRUE is returned.
1014 * If the match was obtained using the DFA algorithm, that is using
1015 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1016 * position is not that of a set of parentheses but that of a matched
1017 * substring. Substrings are matched in reverse order of length, so
1018 * 0 is the longest match.
1020 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
1021 * the position cannot be fetched, @start_pos and @end_pos are left
1027 g_match_info_fetch_pos (const GMatchInfo *match_info,
1032 g_return_val_if_fail (match_info != NULL, FALSE);
1033 g_return_val_if_fail (match_num >= 0, FALSE);
1035 /* make sure the sub expression number they're requesting is less than
1036 * the total number of sub expressions that were matched. */
1037 if (match_num >= match_info->matches)
1040 if (start_pos != NULL)
1041 *start_pos = match_info->offsets[2 * match_num];
1043 if (end_pos != NULL)
1044 *end_pos = match_info->offsets[2 * match_num + 1];
1050 * Returns number of first matched subpattern with name @name.
1051 * There may be more than one in case when DUPNAMES is used,
1052 * and not all subpatterns with that name match;
1053 * pcre_get_stringnumber() does not work in that case.
1056 get_matched_substring_number (const GMatchInfo *match_info,
1060 gchar *first, *last;
1063 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
1064 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
1066 /* This code is copied from pcre_get.c: get_first_set() */
1067 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
1075 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
1077 gint n = (entry[0] << 8) + entry[1];
1078 if (match_info->offsets[n*2] >= 0)
1082 return (first[0] << 8) + first[1];
1086 * g_match_info_fetch_named:
1087 * @match_info: #GMatchInfo structure
1088 * @name: name of the subexpression
1090 * Retrieves the text matching the capturing parentheses named @name.
1092 * If @name is a valid sub pattern name but it didn't match anything
1093 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1094 * then an empty string is returned.
1096 * The string is fetched from the string passed to the match function,
1097 * so you cannot call this function after freeing the string.
1099 * Returns: (allow-none): The matched substring, or %NULL if an error
1100 * occurred. You have to free the string yourself
1105 g_match_info_fetch_named (const GMatchInfo *match_info,
1108 /* we cannot use pcre_get_named_substring() because it allocates the
1109 * string using pcre_malloc(). */
1112 g_return_val_if_fail (match_info != NULL, NULL);
1113 g_return_val_if_fail (name != NULL, NULL);
1115 num = get_matched_substring_number (match_info, name);
1119 return g_match_info_fetch (match_info, num);
1123 * g_match_info_fetch_named_pos:
1124 * @match_info: #GMatchInfo structure
1125 * @name: name of the subexpression
1126 * @start_pos: (out) (allow-none): pointer to location where to store
1127 * the start position, or %NULL
1128 * @end_pos: (out) (allow-none): pointer to location where to store
1129 * the end position, or %NULL
1131 * Retrieves the position in bytes of the capturing parentheses named @name.
1133 * If @name is a valid sub pattern name but it didn't match anything
1134 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1135 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1137 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1138 * If the position cannot be fetched, @start_pos and @end_pos
1139 * are left unchanged.
1144 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
1151 g_return_val_if_fail (match_info != NULL, FALSE);
1152 g_return_val_if_fail (name != NULL, FALSE);
1154 num = get_matched_substring_number (match_info, name);
1158 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
1162 * g_match_info_fetch_all:
1163 * @match_info: a #GMatchInfo structure
1165 * Bundles up pointers to each of the matching substrings from a match
1166 * and stores them in an array of gchar pointers. The first element in
1167 * the returned array is the match number 0, i.e. the entire matched
1170 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1171 * "b" against "(a)?b") then an empty string is inserted.
1173 * If the last match was obtained using the DFA algorithm, that is using
1174 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1175 * strings are not that matched by sets of parentheses but that of the
1176 * matched substring. Substrings are matched in reverse order of length,
1177 * so the first one is the longest match.
1179 * The strings are fetched from the string passed to the match function,
1180 * so you cannot call this function after freeing the string.
1182 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
1183 * It must be freed using g_strfreev(). If the previous match failed
1189 g_match_info_fetch_all (const GMatchInfo *match_info)
1191 /* we cannot use pcre_get_substring_list() because the returned value
1192 * isn't suitable for g_strfreev(). */
1196 g_return_val_if_fail (match_info != NULL, NULL);
1198 if (match_info->matches < 0)
1201 result = g_new (gchar *, match_info->matches + 1);
1202 for (i = 0; i < match_info->matches; i++)
1203 result[i] = g_match_info_fetch (match_info, i);
1213 g_regex_error_quark (void)
1215 static GQuark error_quark = 0;
1217 if (error_quark == 0)
1218 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1227 * Increases reference count of @regex by 1.
1234 g_regex_ref (GRegex *regex)
1236 g_return_val_if_fail (regex != NULL, NULL);
1237 g_atomic_int_inc (®ex->ref_count);
1245 * Decreases reference count of @regex by 1. When reference count drops
1246 * to zero, it frees all the memory associated with the regex structure.
1251 g_regex_unref (GRegex *regex)
1253 g_return_if_fail (regex != NULL);
1255 if (g_atomic_int_dec_and_test (®ex->ref_count))
1257 g_free (regex->pattern);
1258 if (regex->pcre_re != NULL)
1259 pcre_free (regex->pcre_re);
1260 if (regex->extra != NULL)
1261 pcre_free (regex->extra);
1268 * @pattern: the regular expression
1269 * @compile_options: compile options for the regular expression, or 0
1270 * @match_options: match options for the regular expression, or 0
1271 * @error: return location for a #GError
1273 * Compiles the regular expression to an internal form, and does
1274 * the initial setup of the #GRegex structure.
1276 * Returns: a #GRegex structure. Call g_regex_unref() when you
1282 g_regex_new (const gchar *pattern,
1283 GRegexCompileFlags compile_options,
1284 GRegexMatchFlags match_options,
1289 const gchar *errmsg;
1292 gboolean optimize = FALSE;
1293 static volatile gsize initialised = 0;
1294 unsigned long int pcre_compile_options;
1295 GRegexCompileFlags nonpcre_compile_options;
1297 g_return_val_if_fail (pattern != NULL, NULL);
1298 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1299 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1300 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1302 if (g_once_init_enter (&initialised))
1304 int supports_utf8, supports_ucp;
1306 pcre_config (PCRE_CONFIG_UTF8, &supports_utf8);
1308 g_critical (_("PCRE library is compiled without UTF8 support"));
1310 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &supports_ucp);
1312 g_critical (_("PCRE library is compiled without UTF8 properties support"));
1314 g_once_init_leave (&initialised, supports_utf8 && supports_ucp ? 1 : 2);
1317 if (G_UNLIKELY (initialised != 1))
1319 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE,
1320 _("PCRE library is compiled with incompatible options"));
1324 nonpcre_compile_options = compile_options & G_REGEX_COMPILE_NONPCRE_MASK;
1326 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1327 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1328 if (compile_options & G_REGEX_OPTIMIZE)
1331 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1332 * instead uses UTF-8 only if required with PCRE_UTF8. */
1333 if (compile_options & G_REGEX_RAW)
1336 compile_options &= ~G_REGEX_RAW;
1341 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1342 match_options |= PCRE_NO_UTF8_CHECK;
1345 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1346 * not for the system one. */
1347 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1348 !(compile_options & G_REGEX_NEWLINE_LF))
1350 compile_options |= PCRE_NEWLINE_ANY;
1353 compile_options |= PCRE_UCP;
1355 /* PCRE_BSR_UNICODE is the default for the internal PCRE but
1356 * possibly not for the system one.
1358 if (~compile_options & G_REGEX_BSR_ANYCRLF)
1359 compile_options |= PCRE_BSR_UNICODE;
1361 /* compile the pattern */
1362 re = pcre_compile2 (pattern, compile_options, &errcode,
1363 &errmsg, &erroffset, NULL);
1365 /* if the compilation failed, set the error member and return
1371 /* Translate the PCRE error code to GRegexError and use a translated
1372 * error message if possible */
1373 translate_compile_error (&errcode, &errmsg);
1375 /* PCRE uses byte offsets but we want to show character offsets */
1376 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1378 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1379 _("Error while compiling regular "
1380 "expression %s at char %d: %s"),
1381 pattern, erroffset, errmsg);
1382 g_propagate_error (error, tmp_error);
1387 /* For options set at the beginning of the pattern, pcre puts them into
1388 * compile options, e.g. "(?i)foo" will make the pcre structure store
1389 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1390 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1391 compile_options = pcre_compile_options & G_REGEX_COMPILE_PCRE_MASK;
1393 /* Don't leak PCRE_NEWLINE_ANY, which is part of PCRE_NEWLINE_ANYCRLF */
1394 if ((pcre_compile_options & PCRE_NEWLINE_ANYCRLF) != PCRE_NEWLINE_ANYCRLF)
1395 compile_options &= ~PCRE_NEWLINE_ANY;
1397 compile_options |= nonpcre_compile_options;
1399 if (!(compile_options & G_REGEX_DUPNAMES))
1401 gboolean jchanged = FALSE;
1402 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1404 compile_options |= G_REGEX_DUPNAMES;
1407 regex = g_new0 (GRegex, 1);
1408 regex->ref_count = 1;
1409 regex->pattern = g_strdup (pattern);
1410 regex->pcre_re = re;
1411 regex->compile_opts = compile_options;
1412 regex->match_opts = match_options;
1416 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1419 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1420 G_REGEX_ERROR_OPTIMIZE,
1421 _("Error while optimizing "
1422 "regular expression %s: %s"),
1425 g_propagate_error (error, tmp_error);
1427 g_regex_unref (regex);
1436 * g_regex_get_pattern:
1437 * @regex: a #GRegex structure
1439 * Gets the pattern string associated with @regex, i.e. a copy of
1440 * the string passed to g_regex_new().
1442 * Returns: the pattern of @regex
1447 g_regex_get_pattern (const GRegex *regex)
1449 g_return_val_if_fail (regex != NULL, NULL);
1451 return regex->pattern;
1455 * g_regex_get_max_backref:
1458 * Returns the number of the highest back reference
1459 * in the pattern, or 0 if the pattern does not contain
1462 * Returns: the number of the highest back reference
1467 g_regex_get_max_backref (const GRegex *regex)
1471 pcre_fullinfo (regex->pcre_re, regex->extra,
1472 PCRE_INFO_BACKREFMAX, &value);
1478 * g_regex_get_capture_count:
1481 * Returns the number of capturing subpatterns in the pattern.
1483 * Returns: the number of capturing subpatterns
1488 g_regex_get_capture_count (const GRegex *regex)
1492 pcre_fullinfo (regex->pcre_re, regex->extra,
1493 PCRE_INFO_CAPTURECOUNT, &value);
1499 * g_regex_get_has_cr_or_lf:
1500 * @regex: a #GRegex structure
1502 * Checks whether the pattern contains explicit CR or LF references.
1504 * Returns: %TRUE if the pattern contains explicit CR or LF references
1509 g_regex_get_has_cr_or_lf (const GRegex *regex)
1513 pcre_fullinfo (regex->pcre_re, regex->extra,
1514 PCRE_INFO_HASCRORLF, &value);
1520 * g_regex_get_compile_flags:
1523 * Returns the compile options that @regex was created with.
1525 * Returns: flags from #GRegexCompileFlags
1530 g_regex_get_compile_flags (const GRegex *regex)
1532 g_return_val_if_fail (regex != NULL, 0);
1534 return regex->compile_opts;
1538 * g_regex_get_match_flags:
1541 * Returns the match options that @regex was created with.
1543 * Returns: flags from #GRegexMatchFlags
1548 g_regex_get_match_flags (const GRegex *regex)
1550 g_return_val_if_fail (regex != NULL, 0);
1552 return regex->match_opts & G_REGEX_MATCH_MASK;
1556 * g_regex_match_simple:
1557 * @pattern: the regular expression
1558 * @string: the string to scan for matches
1559 * @compile_options: compile options for the regular expression, or 0
1560 * @match_options: match options, or 0
1562 * Scans for a match in @string for @pattern.
1564 * This function is equivalent to g_regex_match() but it does not
1565 * require to compile the pattern with g_regex_new(), avoiding some
1566 * lines of code when you need just to do a match without extracting
1567 * substrings, capture counts, and so on.
1569 * If this function is to be called on the same @pattern more than
1570 * once, it's more efficient to compile the pattern once with
1571 * g_regex_new() and then use g_regex_match().
1573 * Returns: %TRUE if the string matched, %FALSE otherwise
1578 g_regex_match_simple (const gchar *pattern,
1579 const gchar *string,
1580 GRegexCompileFlags compile_options,
1581 GRegexMatchFlags match_options)
1586 regex = g_regex_new (pattern, compile_options, 0, NULL);
1589 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1590 g_regex_unref (regex);
1596 * @regex: a #GRegex structure from g_regex_new()
1597 * @string: the string to scan for matches
1598 * @match_options: match options
1599 * @match_info: (out) (allow-none): pointer to location where to store
1600 * the #GMatchInfo, or %NULL if you do not need it
1602 * Scans for a match in string for the pattern in @regex.
1603 * The @match_options are combined with the match options specified
1604 * when the @regex structure was created, letting you have more
1605 * flexibility in reusing #GRegex structures.
1607 * A #GMatchInfo structure, used to get information on the match,
1608 * is stored in @match_info if not %NULL. Note that if @match_info
1609 * is not %NULL then it is created even if the function returns %FALSE,
1610 * i.e. you must free it regardless if regular expression actually matched.
1612 * To retrieve all the non-overlapping matches of the pattern in
1613 * string you can use g_match_info_next().
1617 * print_uppercase_words (const gchar *string)
1619 * /* Print all uppercase-only words. */
1621 * GMatchInfo *match_info;
1623 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1624 * g_regex_match (regex, string, 0, &match_info);
1625 * while (g_match_info_matches (match_info))
1627 * gchar *word = g_match_info_fetch (match_info, 0);
1628 * g_print ("Found: %s\n", word);
1630 * g_match_info_next (match_info, NULL);
1632 * g_match_info_free (match_info);
1633 * g_regex_unref (regex);
1637 * @string is not copied and is used in #GMatchInfo internally. If
1638 * you use any #GMatchInfo method (except g_match_info_free()) after
1639 * freeing or modifying @string then the behaviour is undefined.
1641 * Returns: %TRUE is the string matched, %FALSE otherwise
1646 g_regex_match (const GRegex *regex,
1647 const gchar *string,
1648 GRegexMatchFlags match_options,
1649 GMatchInfo **match_info)
1651 return g_regex_match_full (regex, string, -1, 0, match_options,
1656 * g_regex_match_full:
1657 * @regex: a #GRegex structure from g_regex_new()
1658 * @string: (array length=string_len): the string to scan for matches
1659 * @string_len: the length of @string, or -1 if @string is nul-terminated
1660 * @start_position: starting index of the string to match
1661 * @match_options: match options
1662 * @match_info: (out) (allow-none): pointer to location where to store
1663 * the #GMatchInfo, or %NULL if you do not need it
1664 * @error: location to store the error occurring, or %NULL to ignore errors
1666 * Scans for a match in string for the pattern in @regex.
1667 * The @match_options are combined with the match options specified
1668 * when the @regex structure was created, letting you have more
1669 * flexibility in reusing #GRegex structures.
1671 * Setting @start_position differs from just passing over a shortened
1672 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1673 * that begins with any kind of lookbehind assertion, such as "\b".
1675 * A #GMatchInfo structure, used to get information on the match, is
1676 * stored in @match_info if not %NULL. Note that if @match_info is
1677 * not %NULL then it is created even if the function returns %FALSE,
1678 * i.e. you must free it regardless if regular expression actually
1681 * @string is not copied and is used in #GMatchInfo internally. If
1682 * you use any #GMatchInfo method (except g_match_info_free()) after
1683 * freeing or modifying @string then the behaviour is undefined.
1685 * To retrieve all the non-overlapping matches of the pattern in
1686 * string you can use g_match_info_next().
1690 * print_uppercase_words (const gchar *string)
1692 * /* Print all uppercase-only words. */
1694 * GMatchInfo *match_info;
1695 * GError *error = NULL;
1697 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1698 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1699 * while (g_match_info_matches (match_info))
1701 * gchar *word = g_match_info_fetch (match_info, 0);
1702 * g_print ("Found: %s\n", word);
1704 * g_match_info_next (match_info, &error);
1706 * g_match_info_free (match_info);
1707 * g_regex_unref (regex);
1708 * if (error != NULL)
1710 * g_printerr ("Error while matching: %s\n", error->message);
1711 * g_error_free (error);
1716 * Returns: %TRUE is the string matched, %FALSE otherwise
1721 g_regex_match_full (const GRegex *regex,
1722 const gchar *string,
1724 gint start_position,
1725 GRegexMatchFlags match_options,
1726 GMatchInfo **match_info,
1732 g_return_val_if_fail (regex != NULL, FALSE);
1733 g_return_val_if_fail (string != NULL, FALSE);
1734 g_return_val_if_fail (start_position >= 0, FALSE);
1735 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1736 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1738 info = match_info_new (regex, string, string_len, start_position,
1739 match_options, FALSE);
1740 match_ok = g_match_info_next (info, error);
1741 if (match_info != NULL)
1744 g_match_info_free (info);
1750 * g_regex_match_all:
1751 * @regex: a #GRegex structure from g_regex_new()
1752 * @string: the string to scan for matches
1753 * @match_options: match options
1754 * @match_info: (out) (allow-none): pointer to location where to store
1755 * the #GMatchInfo, or %NULL if you do not need it
1757 * Using the standard algorithm for regular expression matching only
1758 * the longest match in the string is retrieved. This function uses
1759 * a different algorithm so it can retrieve all the possible matches.
1760 * For more documentation see g_regex_match_all_full().
1762 * A #GMatchInfo structure, used to get information on the match, is
1763 * stored in @match_info if not %NULL. Note that if @match_info is
1764 * not %NULL then it is created even if the function returns %FALSE,
1765 * i.e. you must free it regardless if regular expression actually
1768 * @string is not copied and is used in #GMatchInfo internally. If
1769 * you use any #GMatchInfo method (except g_match_info_free()) after
1770 * freeing or modifying @string then the behaviour is undefined.
1772 * Returns: %TRUE is the string matched, %FALSE otherwise
1777 g_regex_match_all (const GRegex *regex,
1778 const gchar *string,
1779 GRegexMatchFlags match_options,
1780 GMatchInfo **match_info)
1782 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1787 * g_regex_match_all_full:
1788 * @regex: a #GRegex structure from g_regex_new()
1789 * @string: (array length=string_len): the string to scan for matches
1790 * @string_len: the length of @string, or -1 if @string is nul-terminated
1791 * @start_position: starting index of the string to match
1792 * @match_options: match options
1793 * @match_info: (out) (allow-none): pointer to location where to store
1794 * the #GMatchInfo, or %NULL if you do not need it
1795 * @error: location to store the error occurring, or %NULL to ignore errors
1797 * Using the standard algorithm for regular expression matching only
1798 * the longest match in the string is retrieved, it is not possible
1799 * to obtain all the available matches. For instance matching
1800 * "<a> <b> <c>" against the pattern "<.*>"
1801 * you get "<a> <b> <c>".
1803 * This function uses a different algorithm (called DFA, i.e. deterministic
1804 * finite automaton), so it can retrieve all the possible matches, all
1805 * starting at the same point in the string. For instance matching
1806 * "<a> <b> <c>" against the pattern "<.*>"
1807 * you would obtain three matches: "<a> <b> <c>",
1808 * "<a> <b>" and "<a>".
1810 * The number of matched strings is retrieved using
1811 * g_match_info_get_match_count(). To obtain the matched strings and
1812 * their position you can use, respectively, g_match_info_fetch() and
1813 * g_match_info_fetch_pos(). Note that the strings are returned in
1814 * reverse order of length; that is, the longest matching string is
1817 * Note that the DFA algorithm is slower than the standard one and it
1818 * is not able to capture substrings, so backreferences do not work.
1820 * Setting @start_position differs from just passing over a shortened
1821 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1822 * that begins with any kind of lookbehind assertion, such as "\b".
1824 * A #GMatchInfo structure, used to get information on the match, is
1825 * stored in @match_info if not %NULL. Note that if @match_info is
1826 * not %NULL then it is created even if the function returns %FALSE,
1827 * i.e. you must free it regardless if regular expression actually
1830 * @string is not copied and is used in #GMatchInfo internally. If
1831 * you use any #GMatchInfo method (except g_match_info_free()) after
1832 * freeing or modifying @string then the behaviour is undefined.
1834 * Returns: %TRUE is the string matched, %FALSE otherwise
1839 g_regex_match_all_full (const GRegex *regex,
1840 const gchar *string,
1842 gint start_position,
1843 GRegexMatchFlags match_options,
1844 GMatchInfo **match_info,
1850 g_return_val_if_fail (regex != NULL, FALSE);
1851 g_return_val_if_fail (string != NULL, FALSE);
1852 g_return_val_if_fail (start_position >= 0, FALSE);
1853 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1854 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1856 info = match_info_new (regex, string, string_len, start_position,
1857 match_options, TRUE);
1863 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1864 info->string, info->string_len,
1866 regex->match_opts | match_options,
1867 info->offsets, info->n_offsets,
1868 info->workspace, info->n_workspace);
1869 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1871 /* info->workspace is too small. */
1872 info->n_workspace *= 2;
1873 info->workspace = g_realloc (info->workspace,
1874 info->n_workspace * sizeof (gint));
1877 else if (info->matches == 0)
1879 /* info->offsets is too small. */
1880 info->n_offsets *= 2;
1881 info->offsets = g_realloc (info->offsets,
1882 info->n_offsets * sizeof (gint));
1885 else if (IS_PCRE_ERROR (info->matches))
1887 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1888 _("Error while matching regular expression %s: %s"),
1889 regex->pattern, match_error (info->matches));
1893 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1896 if (match_info != NULL)
1899 g_match_info_free (info);
1901 return info->matches >= 0;
1905 * g_regex_get_string_number:
1906 * @regex: #GRegex structure
1907 * @name: name of the subexpression
1909 * Retrieves the number of the subexpression named @name.
1911 * Returns: The number of the subexpression or -1 if @name
1917 g_regex_get_string_number (const GRegex *regex,
1922 g_return_val_if_fail (regex != NULL, -1);
1923 g_return_val_if_fail (name != NULL, -1);
1925 num = pcre_get_stringnumber (regex->pcre_re, name);
1926 if (num == PCRE_ERROR_NOSUBSTRING)
1933 * g_regex_split_simple:
1934 * @pattern: the regular expression
1935 * @string: the string to scan for matches
1936 * @compile_options: compile options for the regular expression, or 0
1937 * @match_options: match options, or 0
1939 * Breaks the string on the pattern, and returns an array of
1940 * the tokens. If the pattern contains capturing parentheses,
1941 * then the text for each of the substrings will also be returned.
1942 * If the pattern does not match anywhere in the string, then the
1943 * whole string is returned as the first token.
1945 * This function is equivalent to g_regex_split() but it does
1946 * not require to compile the pattern with g_regex_new(), avoiding
1947 * some lines of code when you need just to do a split without
1948 * extracting substrings, capture counts, and so on.
1950 * If this function is to be called on the same @pattern more than
1951 * once, it's more efficient to compile the pattern once with
1952 * g_regex_new() and then use g_regex_split().
1954 * As a special case, the result of splitting the empty string ""
1955 * is an empty vector, not a vector containing a single string.
1956 * The reason for this special case is that being able to represent
1957 * a empty vector is typically more useful than consistent handling
1958 * of empty elements. If you do need to represent empty elements,
1959 * you'll need to check for the empty string before calling this
1962 * A pattern that can match empty strings splits @string into
1963 * separate characters wherever it matches the empty string between
1964 * characters. For example splitting "ab c" using as a separator
1965 * "\s*", you will get "a", "b" and "c".
1967 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1972 g_regex_split_simple (const gchar *pattern,
1973 const gchar *string,
1974 GRegexCompileFlags compile_options,
1975 GRegexMatchFlags match_options)
1980 regex = g_regex_new (pattern, compile_options, 0, NULL);
1984 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1985 g_regex_unref (regex);
1991 * @regex: a #GRegex structure
1992 * @string: the string to split with the pattern
1993 * @match_options: match time option flags
1995 * Breaks the string on the pattern, and returns an array of the tokens.
1996 * If the pattern contains capturing parentheses, then the text for each
1997 * of the substrings will also be returned. If the pattern does not match
1998 * anywhere in the string, then the whole string is returned as the first
2001 * As a special case, the result of splitting the empty string "" is an
2002 * empty vector, not a vector containing a single string. The reason for
2003 * this special case is that being able to represent a empty vector is
2004 * typically more useful than consistent handling of empty elements. If
2005 * you do need to represent empty elements, you'll need to check for the
2006 * empty string before calling this function.
2008 * A pattern that can match empty strings splits @string into separate
2009 * characters wherever it matches the empty string between characters.
2010 * For example splitting "ab c" using as a separator "\s*", you will get
2013 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2018 g_regex_split (const GRegex *regex,
2019 const gchar *string,
2020 GRegexMatchFlags match_options)
2022 return g_regex_split_full (regex, string, -1, 0,
2023 match_options, 0, NULL);
2027 * g_regex_split_full:
2028 * @regex: a #GRegex structure
2029 * @string: (array length=string_len): the string to split with the pattern
2030 * @string_len: the length of @string, or -1 if @string is nul-terminated
2031 * @start_position: starting index of the string to match
2032 * @match_options: match time option flags
2033 * @max_tokens: the maximum number of tokens to split @string into.
2034 * If this is less than 1, the string is split completely
2035 * @error: return location for a #GError
2037 * Breaks the string on the pattern, and returns an array of the tokens.
2038 * If the pattern contains capturing parentheses, then the text for each
2039 * of the substrings will also be returned. If the pattern does not match
2040 * anywhere in the string, then the whole string is returned as the first
2043 * As a special case, the result of splitting the empty string "" is an
2044 * empty vector, not a vector containing a single string. The reason for
2045 * this special case is that being able to represent a empty vector is
2046 * typically more useful than consistent handling of empty elements. If
2047 * you do need to represent empty elements, you'll need to check for the
2048 * empty string before calling this function.
2050 * A pattern that can match empty strings splits @string into separate
2051 * characters wherever it matches the empty string between characters.
2052 * For example splitting "ab c" using as a separator "\s*", you will get
2055 * Setting @start_position differs from just passing over a shortened
2056 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2057 * that begins with any kind of lookbehind assertion, such as "\b".
2059 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2064 g_regex_split_full (const GRegex *regex,
2065 const gchar *string,
2067 gint start_position,
2068 GRegexMatchFlags match_options,
2072 GError *tmp_error = NULL;
2073 GMatchInfo *match_info;
2078 /* position of the last separator. */
2079 gint last_separator_end;
2080 /* was the last match 0 bytes long? */
2081 gboolean last_match_is_empty;
2082 /* the returned array of char **s */
2083 gchar **string_list;
2085 g_return_val_if_fail (regex != NULL, NULL);
2086 g_return_val_if_fail (string != NULL, NULL);
2087 g_return_val_if_fail (start_position >= 0, NULL);
2088 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2089 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2091 if (max_tokens <= 0)
2092 max_tokens = G_MAXINT;
2095 string_len = strlen (string);
2097 /* zero-length string */
2098 if (string_len - start_position == 0)
2099 return g_new0 (gchar *, 1);
2101 if (max_tokens == 1)
2103 string_list = g_new0 (gchar *, 2);
2104 string_list[0] = g_strndup (&string[start_position],
2105 string_len - start_position);
2111 last_separator_end = start_position;
2112 last_match_is_empty = FALSE;
2114 match_ok = g_regex_match_full (regex, string, string_len, start_position,
2115 match_options, &match_info, &tmp_error);
2117 while (tmp_error == NULL)
2121 last_match_is_empty =
2122 (match_info->offsets[0] == match_info->offsets[1]);
2124 /* we need to skip empty separators at the same position of the end
2125 * of another separator. e.g. the string is "a b" and the separator
2126 * is " *", so from 1 to 2 we have a match and at position 2 we have
2127 * an empty match. */
2128 if (last_separator_end != match_info->offsets[1])
2133 token = g_strndup (string + last_separator_end,
2134 match_info->offsets[0] - last_separator_end);
2135 list = g_list_prepend (list, token);
2138 /* if there were substrings, these need to be added to
2140 match_count = g_match_info_get_match_count (match_info);
2141 if (match_count > 1)
2143 for (i = 1; i < match_count; i++)
2144 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
2150 /* if there was no match, copy to end of string. */
2151 if (!last_match_is_empty)
2153 gchar *token = g_strndup (string + last_separator_end,
2154 match_info->string_len - last_separator_end);
2155 list = g_list_prepend (list, token);
2157 /* no more tokens, end the loop. */
2161 /* -1 to leave room for the last part. */
2162 if (token_count >= max_tokens - 1)
2164 /* we have reached the maximum number of tokens, so we copy
2165 * the remaining part of the string. */
2166 if (last_match_is_empty)
2168 /* the last match was empty, so we have moved one char
2169 * after the real position to avoid empty matches at the
2171 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
2173 /* the if is needed in the case we have terminated the available
2174 * tokens, but we are at the end of the string, so there are no
2175 * characters left to copy. */
2176 if (string_len > match_info->pos)
2178 gchar *token = g_strndup (string + match_info->pos,
2179 string_len - match_info->pos);
2180 list = g_list_prepend (list, token);
2186 last_separator_end = match_info->pos;
2187 if (last_match_is_empty)
2188 /* if the last match was empty, g_match_info_next() has moved
2189 * forward to avoid infinite loops, but we still need to copy that
2191 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
2193 match_ok = g_match_info_next (match_info, &tmp_error);
2195 g_match_info_free (match_info);
2196 if (tmp_error != NULL)
2198 g_propagate_error (error, tmp_error);
2199 g_list_free_full (list, g_free);
2200 match_info->pos = -1;
2204 string_list = g_new (gchar *, g_list_length (list) + 1);
2206 for (last = g_list_last (list); last; last = g_list_previous (last))
2207 string_list[i++] = last->data;
2208 string_list[i] = NULL;
2217 REPL_TYPE_CHARACTER,
2218 REPL_TYPE_SYMBOLIC_REFERENCE,
2219 REPL_TYPE_NUMERIC_REFERENCE,
2220 REPL_TYPE_CHANGE_CASE
2225 CHANGE_CASE_NONE = 1 << 0,
2226 CHANGE_CASE_UPPER = 1 << 1,
2227 CHANGE_CASE_LOWER = 1 << 2,
2228 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
2229 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
2230 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
2231 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
2232 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
2235 struct _InterpolationData
2241 ChangeCase change_case;
2245 free_interpolation_data (InterpolationData *data)
2247 g_free (data->text);
2251 static const gchar *
2252 expand_escape (const gchar *replacement,
2254 InterpolationData *data,
2259 const gchar *error_detail;
2261 GError *tmp_error = NULL;
2269 data->type = REPL_TYPE_CHARACTER;
2274 data->type = REPL_TYPE_CHARACTER;
2279 data->type = REPL_TYPE_CHARACTER;
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;
2314 h = g_ascii_xdigit_value (*p);
2317 error_detail = _("hexadecimal digit or '}' expected");
2328 for (i = 0; i < 2; i++)
2330 h = g_ascii_xdigit_value (*p);
2333 error_detail = _("hexadecimal digit expected");
2340 data->type = REPL_TYPE_STRING;
2341 data->text = g_new0 (gchar, 8);
2342 g_unichar_to_utf8 (x, data->text);
2346 data->type = REPL_TYPE_CHANGE_CASE;
2347 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2351 data->type = REPL_TYPE_CHANGE_CASE;
2352 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2356 data->type = REPL_TYPE_CHANGE_CASE;
2357 data->change_case = CHANGE_CASE_LOWER;
2361 data->type = REPL_TYPE_CHANGE_CASE;
2362 data->change_case = CHANGE_CASE_UPPER;
2366 data->type = REPL_TYPE_CHANGE_CASE;
2367 data->change_case = CHANGE_CASE_NONE;
2373 error_detail = _("missing '<' in symbolic reference");
2382 error_detail = _("unfinished symbolic reference");
2389 error_detail = _("zero-length symbolic reference");
2392 if (g_ascii_isdigit (*q))
2397 h = g_ascii_digit_value (*q);
2400 error_detail = _("digit expected");
2409 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2416 if (!g_ascii_isalnum (*r))
2418 error_detail = _("illegal symbolic reference");
2425 data->text = g_strndup (q, p - q);
2426 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2431 /* if \0 is followed by a number is an octal number representing a
2432 * character, else it is a numeric reference. */
2433 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2436 p = g_utf8_next_char (p);
2449 for (i = 0; i < 3; i++)
2451 h = g_ascii_digit_value (*p);
2461 if (i == 2 && base == 10)
2467 if (base == 8 || i == 3)
2469 data->type = REPL_TYPE_STRING;
2470 data->text = g_new0 (gchar, 8);
2471 g_unichar_to_utf8 (x, data->text);
2475 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2480 error_detail = _("stray final '\\'");
2484 error_detail = _("unknown escape sequence");
2491 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2492 tmp_error = g_error_new (G_REGEX_ERROR,
2493 G_REGEX_ERROR_REPLACE,
2494 _("Error while parsing replacement "
2495 "text \"%s\" at char %lu: %s"),
2497 (gulong)(p - replacement),
2499 g_propagate_error (error, tmp_error);
2505 split_replacement (const gchar *replacement,
2509 InterpolationData *data;
2510 const gchar *p, *start;
2512 start = p = replacement;
2517 data = g_new0 (InterpolationData, 1);
2518 start = p = expand_escape (replacement, p, data, error);
2521 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2522 free_interpolation_data (data);
2526 list = g_list_prepend (list, data);
2531 if (*p == '\\' || *p == '\0')
2535 data = g_new0 (InterpolationData, 1);
2536 data->text = g_strndup (start, p - start);
2537 data->type = REPL_TYPE_STRING;
2538 list = g_list_prepend (list, data);
2544 return g_list_reverse (list);
2547 /* Change the case of c based on change_case. */
2548 #define CHANGE_CASE(c, change_case) \
2549 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2550 g_unichar_tolower (c) : \
2551 g_unichar_toupper (c))
2554 string_append (GString *string,
2556 ChangeCase *change_case)
2560 if (text[0] == '\0')
2563 if (*change_case == CHANGE_CASE_NONE)
2565 g_string_append (string, text);
2567 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2569 c = g_utf8_get_char (text);
2570 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2571 g_string_append (string, g_utf8_next_char (text));
2572 *change_case = CHANGE_CASE_NONE;
2576 while (*text != '\0')
2578 c = g_utf8_get_char (text);
2579 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2580 text = g_utf8_next_char (text);
2586 interpolate_replacement (const GMatchInfo *match_info,
2591 InterpolationData *idata;
2593 ChangeCase change_case = CHANGE_CASE_NONE;
2595 for (list = data; list; list = list->next)
2598 switch (idata->type)
2600 case REPL_TYPE_STRING:
2601 string_append (result, idata->text, &change_case);
2603 case REPL_TYPE_CHARACTER:
2604 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2605 if (change_case & CHANGE_CASE_SINGLE_MASK)
2606 change_case = CHANGE_CASE_NONE;
2608 case REPL_TYPE_NUMERIC_REFERENCE:
2609 match = g_match_info_fetch (match_info, idata->num);
2612 string_append (result, match, &change_case);
2616 case REPL_TYPE_SYMBOLIC_REFERENCE:
2617 match = g_match_info_fetch_named (match_info, idata->text);
2620 string_append (result, match, &change_case);
2624 case REPL_TYPE_CHANGE_CASE:
2625 change_case = idata->change_case;
2633 /* whether actual match_info is needed for replacement, i.e.
2634 * whether there are references
2637 interpolation_list_needs_match (GList *list)
2639 while (list != NULL)
2641 InterpolationData *data = list->data;
2643 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2644 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2657 * @regex: a #GRegex structure
2658 * @string: (array length=string_len): the string to perform matches against
2659 * @string_len: the length of @string, or -1 if @string is nul-terminated
2660 * @start_position: starting index of the string to match
2661 * @replacement: text to replace each match with
2662 * @match_options: options for the match
2663 * @error: location to store the error occurring, or %NULL to ignore errors
2665 * Replaces all occurrences of the pattern in @regex with the
2666 * replacement text. Backreferences of the form '\number' or
2667 * '\g<number>' in the replacement text are interpolated by the
2668 * number-th captured subexpression of the match, '\g<name>' refers
2669 * to the captured subexpression with the given name. '\0' refers to the
2670 * complete match, but '\0' followed by a number is the octal representation
2671 * of a character. To include a literal '\' in the replacement, write '\\'.
2672 * There are also escapes that changes the case of the following text:
2675 * <varlistentry><term>\l</term>
2677 * <para>Convert to lower case the next character</para>
2680 * <varlistentry><term>\u</term>
2682 * <para>Convert to upper case the next character</para>
2685 * <varlistentry><term>\L</term>
2687 * <para>Convert to lower case till \E</para>
2690 * <varlistentry><term>\U</term>
2692 * <para>Convert to upper case till \E</para>
2695 * <varlistentry><term>\E</term>
2697 * <para>End case modification</para>
2702 * If you do not need to use backreferences use g_regex_replace_literal().
2704 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2705 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2706 * you can use g_regex_replace_literal().
2708 * Setting @start_position differs from just passing over a shortened
2709 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2710 * begins with any kind of lookbehind assertion, such as "\b".
2712 * Returns: a newly allocated string containing the replacements
2717 g_regex_replace (const GRegex *regex,
2718 const gchar *string,
2720 gint start_position,
2721 const gchar *replacement,
2722 GRegexMatchFlags match_options,
2727 GError *tmp_error = NULL;
2729 g_return_val_if_fail (regex != NULL, NULL);
2730 g_return_val_if_fail (string != NULL, NULL);
2731 g_return_val_if_fail (start_position >= 0, NULL);
2732 g_return_val_if_fail (replacement != NULL, NULL);
2733 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2734 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2736 list = split_replacement (replacement, &tmp_error);
2737 if (tmp_error != NULL)
2739 g_propagate_error (error, tmp_error);
2743 result = g_regex_replace_eval (regex,
2744 string, string_len, start_position,
2746 interpolate_replacement,
2749 if (tmp_error != NULL)
2750 g_propagate_error (error, tmp_error);
2752 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2758 literal_replacement (const GMatchInfo *match_info,
2762 g_string_append (result, data);
2767 * g_regex_replace_literal:
2768 * @regex: a #GRegex structure
2769 * @string: (array length=string_len): the string to perform matches against
2770 * @string_len: the length of @string, or -1 if @string is nul-terminated
2771 * @start_position: starting index of the string to match
2772 * @replacement: text to replace each match with
2773 * @match_options: options for the match
2774 * @error: location to store the error occurring, or %NULL to ignore errors
2776 * Replaces all occurrences of the pattern in @regex with the
2777 * replacement text. @replacement is replaced literally, to
2778 * include backreferences use g_regex_replace().
2780 * Setting @start_position differs from just passing over a
2781 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2782 * case of a pattern that begins with any kind of lookbehind
2783 * assertion, such as "\b".
2785 * Returns: a newly allocated string containing the replacements
2790 g_regex_replace_literal (const GRegex *regex,
2791 const gchar *string,
2793 gint start_position,
2794 const gchar *replacement,
2795 GRegexMatchFlags match_options,
2798 g_return_val_if_fail (replacement != NULL, NULL);
2799 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2801 return g_regex_replace_eval (regex,
2802 string, string_len, start_position,
2804 literal_replacement,
2805 (gpointer)replacement,
2810 * g_regex_replace_eval:
2811 * @regex: a #GRegex structure from g_regex_new()
2812 * @string: (array length=string_len): string to perform matches against
2813 * @string_len: the length of @string, or -1 if @string is nul-terminated
2814 * @start_position: starting index of the string to match
2815 * @match_options: options for the match
2816 * @eval: a function to call for each match
2817 * @user_data: user data to pass to the function
2818 * @error: location to store the error occurring, or %NULL to ignore errors
2820 * Replaces occurrences of the pattern in regex with the output of
2821 * @eval for that occurrence.
2823 * Setting @start_position differs from just passing over a shortened
2824 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2825 * that begins with any kind of lookbehind assertion, such as "\b".
2827 * The following example uses g_regex_replace_eval() to replace multiple
2831 * eval_cb (const GMatchInfo *info,
2838 * match = g_match_info_fetch (info, 0);
2839 * r = g_hash_table_lookup ((GHashTable *)data, match);
2840 * g_string_append (res, r);
2852 * h = g_hash_table_new (g_str_hash, g_str_equal);
2854 * g_hash_table_insert (h, "1", "ONE");
2855 * g_hash_table_insert (h, "2", "TWO");
2856 * g_hash_table_insert (h, "3", "THREE");
2857 * g_hash_table_insert (h, "4", "FOUR");
2859 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2860 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2861 * g_hash_table_destroy (h);
2866 * Returns: a newly allocated string containing the replacements
2871 g_regex_replace_eval (const GRegex *regex,
2872 const gchar *string,
2874 gint start_position,
2875 GRegexMatchFlags match_options,
2876 GRegexEvalCallback eval,
2880 GMatchInfo *match_info;
2883 gboolean done = FALSE;
2884 GError *tmp_error = NULL;
2886 g_return_val_if_fail (regex != NULL, NULL);
2887 g_return_val_if_fail (string != NULL, NULL);
2888 g_return_val_if_fail (start_position >= 0, NULL);
2889 g_return_val_if_fail (eval != NULL, NULL);
2890 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2893 string_len = strlen (string);
2895 result = g_string_sized_new (string_len);
2897 /* run down the string making matches. */
2898 g_regex_match_full (regex, string, string_len, start_position,
2899 match_options, &match_info, &tmp_error);
2900 while (!done && g_match_info_matches (match_info))
2902 g_string_append_len (result,
2904 match_info->offsets[0] - str_pos);
2905 done = (*eval) (match_info, result, user_data);
2906 str_pos = match_info->offsets[1];
2907 g_match_info_next (match_info, &tmp_error);
2909 g_match_info_free (match_info);
2910 if (tmp_error != NULL)
2912 g_propagate_error (error, tmp_error);
2913 g_string_free (result, TRUE);
2917 g_string_append_len (result, string + str_pos, string_len - str_pos);
2918 return g_string_free (result, FALSE);
2922 * g_regex_check_replacement:
2923 * @replacement: the replacement string
2924 * @has_references: (out) (allow-none): location to store information about
2925 * references in @replacement or %NULL
2926 * @error: location to store error
2928 * Checks whether @replacement is a valid replacement string
2929 * (see g_regex_replace()), i.e. that all escape sequences in
2932 * If @has_references is not %NULL then @replacement is checked
2933 * for pattern references. For instance, replacement text 'foo\n'
2934 * does not contain references and may be evaluated without information
2935 * about actual match, but '\0\1' (whole match followed by first
2936 * subpattern) requires valid #GMatchInfo object.
2938 * Returns: whether @replacement is a valid replacement string
2943 g_regex_check_replacement (const gchar *replacement,
2944 gboolean *has_references,
2950 list = split_replacement (replacement, &tmp);
2954 g_propagate_error (error, tmp);
2959 *has_references = interpolation_list_needs_match (list);
2961 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2967 * g_regex_escape_nul:
2968 * @string: the string to escape
2969 * @length: the length of @string
2971 * Escapes the nul characters in @string to "\x00". It can be used
2972 * to compile a regex with embedded nul characters.
2974 * For completeness, @length can be -1 for a nul-terminated string.
2975 * In this case the output string will be of course equal to @string.
2977 * Returns: a newly-allocated escaped string
2982 g_regex_escape_nul (const gchar *string,
2986 const gchar *p, *piece_start, *end;
2989 g_return_val_if_fail (string != NULL, NULL);
2992 return g_strdup (string);
2994 end = string + length;
2995 p = piece_start = string;
2996 escaped = g_string_sized_new (length + 1);
3004 if (p != piece_start)
3006 /* copy the previous piece. */
3007 g_string_append_len (escaped, piece_start, p - piece_start);
3009 if ((backslashes & 1) == 0)
3010 g_string_append_c (escaped, '\\');
3011 g_string_append_c (escaped, 'x');
3012 g_string_append_c (escaped, '0');
3013 g_string_append_c (escaped, '0');
3023 p = g_utf8_next_char (p);
3028 if (piece_start < end)
3029 g_string_append_len (escaped, piece_start, end - piece_start);
3031 return g_string_free (escaped, FALSE);
3035 * g_regex_escape_string:
3036 * @string: (array length=length): the string to escape
3037 * @length: the length of @string, or -1 if @string is nul-terminated
3039 * Escapes the special characters used for regular expressions
3040 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
3041 * function is useful to dynamically generate regular expressions.
3043 * @string can contain nul characters that are replaced with "\0",
3044 * in this case remember to specify the correct length of @string
3047 * Returns: a newly-allocated escaped string
3052 g_regex_escape_string (const gchar *string,
3056 const char *p, *piece_start, *end;
3058 g_return_val_if_fail (string != NULL, NULL);
3061 length = strlen (string);
3063 end = string + length;
3064 p = piece_start = string;
3065 escaped = g_string_sized_new (length + 1);
3086 if (p != piece_start)
3087 /* copy the previous piece. */
3088 g_string_append_len (escaped, piece_start, p - piece_start);
3089 g_string_append_c (escaped, '\\');
3091 g_string_append_c (escaped, '0');
3093 g_string_append_c (escaped, *p);
3097 p = g_utf8_next_char (p);
3102 if (piece_start < end)
3103 g_string_append_len (escaped, piece_start, end - piece_start);
3105 return g_string_free (escaped, FALSE);