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 * Creating and manipulating the same #GRegex structure from different
92 * threads is not a problem as #GRegex does not modify its internal
93 * state between creation and destruction, on the other hand #GMatchInfo
96 * The regular expressions low-level functionalities are obtained through
97 * the excellent <ulink url="http://www.pcre.org/">PCRE</ulink> library
98 * written by Philip Hazel.
101 /* Mask of all the possible values for GRegexCompileFlags. */
102 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
103 G_REGEX_MULTILINE | \
107 G_REGEX_DOLLAR_ENDONLY | \
110 G_REGEX_NO_AUTO_CAPTURE | \
113 G_REGEX_NEWLINE_CR | \
114 G_REGEX_NEWLINE_LF | \
115 G_REGEX_NEWLINE_CRLF | \
116 G_REGEX_NEWLINE_ANYCRLF | \
119 /* Mask of all the possible values for GRegexMatchFlags. */
120 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
121 G_REGEX_MATCH_NOTBOL | \
122 G_REGEX_MATCH_NOTEOL | \
123 G_REGEX_MATCH_NOTEMPTY | \
124 G_REGEX_MATCH_PARTIAL | \
125 G_REGEX_MATCH_NEWLINE_CR | \
126 G_REGEX_MATCH_NEWLINE_LF | \
127 G_REGEX_MATCH_NEWLINE_CRLF | \
128 G_REGEX_MATCH_NEWLINE_ANY | \
129 G_REGEX_MATCH_NEWLINE_ANYCRLF)
131 /* we rely on these flags having the same values */
132 G_STATIC_ASSERT (G_REGEX_CASELESS == PCRE_CASELESS);
133 G_STATIC_ASSERT (G_REGEX_MULTILINE == PCRE_MULTILINE);
134 G_STATIC_ASSERT (G_REGEX_DOTALL == PCRE_DOTALL);
135 G_STATIC_ASSERT (G_REGEX_EXTENDED == PCRE_EXTENDED);
136 G_STATIC_ASSERT (G_REGEX_ANCHORED == PCRE_ANCHORED);
137 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY == PCRE_DOLLAR_ENDONLY);
138 G_STATIC_ASSERT (G_REGEX_UNGREEDY == PCRE_UNGREEDY);
139 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE == PCRE_NO_AUTO_CAPTURE);
140 G_STATIC_ASSERT (G_REGEX_DUPNAMES == PCRE_DUPNAMES);
141 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR == PCRE_NEWLINE_CR);
142 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF == PCRE_NEWLINE_LF);
143 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
144 G_STATIC_ASSERT (G_REGEX_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
145 G_STATIC_ASSERT (G_REGEX_BSR_ANYCRLF == PCRE_BSR_ANYCRLF);
147 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED == PCRE_ANCHORED);
148 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL == PCRE_NOTBOL);
149 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL == PCRE_NOTEOL);
150 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY == PCRE_NOTEMPTY);
151 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL == PCRE_PARTIAL);
152 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR == PCRE_NEWLINE_CR);
153 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF == PCRE_NEWLINE_LF);
154 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
155 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY == PCRE_NEWLINE_ANY);
156 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
158 /* if the string is in UTF-8 use g_utf8_ functions, else use
160 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
161 g_utf8_next_char (s) : \
163 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
164 g_utf8_prev_char (s) : \
169 volatile gint ref_count; /* the ref count */
170 GRegex *regex; /* the regex */
171 GRegexMatchFlags match_opts; /* options used at match time on the regex */
172 gint matches; /* number of matching sub patterns */
173 gint pos; /* position in the string where last match left off */
174 gint n_offsets; /* number of offsets */
175 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
176 gint *workspace; /* workspace for pcre_dfa_exec() */
177 gint n_workspace; /* number of workspace elements */
178 const gchar *string; /* string passed to the match function */
179 gssize string_len; /* length of string */
184 volatile gint ref_count; /* the ref count for the immutable part */
185 gchar *pattern; /* the pattern */
186 pcre *pcre_re; /* compiled form of the pattern */
187 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
188 GRegexMatchFlags match_opts; /* options used at match time on the regex */
189 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
192 /* TRUE if ret is an error code, FALSE otherwise. */
193 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
195 typedef struct _InterpolationData InterpolationData;
196 static gboolean interpolation_list_needs_match (GList *list);
197 static gboolean interpolate_replacement (const GMatchInfo *match_info,
200 static GList *split_replacement (const gchar *replacement,
202 static void free_interpolation_data (InterpolationData *data);
206 match_error (gint errcode)
210 case PCRE_ERROR_NOMATCH:
213 case PCRE_ERROR_NULL:
214 /* NULL argument, this should not happen in GRegex */
215 g_warning ("A NULL argument was passed to PCRE");
217 case PCRE_ERROR_BADOPTION:
218 return "bad options";
219 case PCRE_ERROR_BADMAGIC:
220 return _("corrupted object");
221 case PCRE_ERROR_UNKNOWN_OPCODE:
222 return N_("internal error or corrupted object");
223 case PCRE_ERROR_NOMEMORY:
224 return _("out of memory");
225 case PCRE_ERROR_NOSUBSTRING:
226 /* not used by pcre_exec() */
228 case PCRE_ERROR_MATCHLIMIT:
229 return _("backtracking limit reached");
230 case PCRE_ERROR_CALLOUT:
231 /* callouts are not implemented */
233 case PCRE_ERROR_BADUTF8:
234 case PCRE_ERROR_BADUTF8_OFFSET:
235 /* we do not check if strings are valid */
237 case PCRE_ERROR_PARTIAL:
240 case PCRE_ERROR_BADPARTIAL:
241 return _("the pattern contains items not supported for partial matching");
242 case PCRE_ERROR_INTERNAL:
243 return _("internal error");
244 case PCRE_ERROR_BADCOUNT:
245 /* negative ovecsize, this should not happen in GRegex */
246 g_warning ("A negative ovecsize was passed to PCRE");
248 case PCRE_ERROR_DFA_UITEM:
249 return _("the pattern contains items not supported for partial matching");
250 case PCRE_ERROR_DFA_UCOND:
251 return _("back references as conditions are not supported for partial matching");
252 case PCRE_ERROR_DFA_UMLIMIT:
253 /* the match_field field is not used in GRegex */
255 case PCRE_ERROR_DFA_WSSIZE:
256 /* handled expanding the workspace */
258 case PCRE_ERROR_DFA_RECURSE:
259 case PCRE_ERROR_RECURSIONLIMIT:
260 return _("recursion limit reached");
261 case PCRE_ERROR_BADNEWLINE:
262 return _("invalid combination of newline flags");
263 case PCRE_ERROR_BADOFFSET:
264 return _("bad offset");
265 case PCRE_ERROR_SHORTUTF8:
266 return _("short utf8");
267 case PCRE_ERROR_RECURSELOOP:
268 return _("recursion loop");
272 return _("unknown error");
276 translate_compile_error (gint *errcode, const gchar **errmsg)
278 /* Compile errors are created adding 100 to the error code returned
280 * If errcode is known we put the translatable error message in
281 * erromsg. If errcode is unknown we put the generic
282 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
283 * untranslated error message returned by PCRE.
284 * Note that there can be more PCRE errors with the same GRegexError
285 * and that some PCRE errors are useless for us.
291 case G_REGEX_ERROR_STRAY_BACKSLASH:
292 *errmsg = _("\\ at end of pattern");
294 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
295 *errmsg = _("\\c at end of pattern");
297 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
298 *errmsg = _("unrecognized character follows \\");
300 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
301 *errmsg = _("numbers out of order in {} quantifier");
303 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
304 *errmsg = _("number too big in {} quantifier");
306 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
307 *errmsg = _("missing terminating ] for character class");
309 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
310 *errmsg = _("invalid escape sequence in character class");
312 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
313 *errmsg = _("range out of order in character class");
315 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
316 *errmsg = _("nothing to repeat");
318 case 111: /* internal error: unexpected repeat */
319 *errcode = G_REGEX_ERROR_INTERNAL;
320 *errmsg = _("unexpected repeat");
322 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
323 *errmsg = _("unrecognized character after (? or (?-");
325 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
326 *errmsg = _("POSIX named classes are supported only within a class");
328 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
329 *errmsg = _("missing terminating )");
331 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
332 *errmsg = _("reference to non-existent subpattern");
334 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
335 *errmsg = _("missing ) after comment");
337 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
338 *errmsg = _("regular expression is too large");
340 case G_REGEX_ERROR_MEMORY_ERROR:
341 *errmsg = _("failed to get memory");
343 case 122: /* unmatched parentheses */
344 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
345 *errmsg = _(") without opening (");
347 case 123: /* internal error: code overflow */
348 *errcode = G_REGEX_ERROR_INTERNAL;
349 *errmsg = _("code overflow");
351 case 124: /* "unrecognized character after (?<\0 */
352 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
353 *errmsg = _("unrecognized character after (?<");
355 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
356 *errmsg = _("lookbehind assertion is not fixed length");
358 case G_REGEX_ERROR_MALFORMED_CONDITION:
359 *errmsg = _("malformed number or name after (?(");
361 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
362 *errmsg = _("conditional group contains more than two branches");
364 case G_REGEX_ERROR_ASSERTION_EXPECTED:
365 *errmsg = _("assertion expected after (?(");
368 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
369 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
370 * sequences here, '(?-54' would be an example for the second group.
372 *errmsg = _("(?R or (?[+-]digits must be followed by )");
374 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
375 *errmsg = _("unknown POSIX class name");
377 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
378 *errmsg = _("POSIX collating elements are not supported");
380 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
381 *errmsg = _("character value in \\x{...} sequence is too large");
383 case G_REGEX_ERROR_INVALID_CONDITION:
384 *errmsg = _("invalid condition (?(0)");
386 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
387 *errmsg = _("\\C not allowed in lookbehind assertion");
389 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
390 /* A number of Perl escapes are not handled by PCRE.
391 * Therefore it explicitly raises ERR37.
393 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
394 *errmsg = _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
396 case G_REGEX_ERROR_INFINITE_LOOP:
397 *errmsg = _("recursive call could loop indefinitely");
399 case 141: /* unrecognized character after (?P\0 */
400 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
401 *errmsg = _("unrecognized character after (?P");
403 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
404 *errmsg = _("missing terminator in subpattern name");
406 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
407 *errmsg = _("two named subpatterns have the same name");
409 case G_REGEX_ERROR_MALFORMED_PROPERTY:
410 *errmsg = _("malformed \\P or \\p sequence");
412 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
413 *errmsg = _("unknown property name after \\P or \\p");
415 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
416 *errmsg = _("subpattern name is too long (maximum 32 characters)");
418 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
419 *errmsg = _("too many named subpatterns (maximum 10,000)");
421 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
422 *errmsg = _("octal value is greater than \\377");
424 case 152: /* internal error: overran compiling workspace */
425 *errcode = G_REGEX_ERROR_INTERNAL;
426 *errmsg = _("overran compiling workspace");
428 case 153: /* internal error: previously-checked referenced subpattern not found */
429 *errcode = G_REGEX_ERROR_INTERNAL;
430 *errmsg = _("previously-checked referenced subpattern not found");
432 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
433 *errmsg = _("DEFINE group contains more than one branch");
435 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
436 *errmsg = _("inconsistent NEWLINE options");
438 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
439 *errmsg = _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
440 "number, or by a plain number");
442 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE:
443 *errmsg = _("a numbered reference must not be zero");
445 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
446 *errmsg = _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
448 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB:
449 *errmsg = _("(*VERB) not recognized");
451 case G_REGEX_ERROR_NUMBER_TOO_BIG:
452 *errmsg = _("number is too bug");
454 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME:
455 *errmsg = _("missing subpattern name after (?&");
457 case G_REGEX_ERROR_MISSING_DIGIT:
458 *errmsg = _("digit expected after (?+");
460 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME:
461 *errmsg = _("different names for subpatterns of the same number are not allowed");
463 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
464 *errmsg = _("(*MARK) must have an argument");
466 case G_REGEX_ERROR_INVALID_CONTROL_CHAR:
467 *errmsg = _( "\\c must be followed by an ASCII character");
469 case G_REGEX_ERROR_MISSING_NAME:
470 *errmsg = _("\\k is not followed by a braced, angle-bracketed, or quoted name");
472 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS:
473 *errmsg = _("\\N is not supported in a class");
475 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES:
476 *errmsg = _("too many forward references");
478 case G_REGEX_ERROR_NAME_TOO_LONG:
479 *errmsg = _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
482 case 116: /* erroffset passed as NULL */
483 /* This should not happen as we never pass a NULL erroffset */
484 g_warning ("erroffset passed as NULL");
485 *errcode = G_REGEX_ERROR_COMPILE;
487 case 117: /* unknown option bit(s) set */
488 /* This should not happen as we check options before passing them
489 * to pcre_compile2() */
490 g_warning ("unknown option bit(s) set");
491 *errcode = G_REGEX_ERROR_COMPILE;
493 case 132: /* this version of PCRE is compiled without UTF support */
494 case 144: /* invalid UTF-8 string */
495 case 145: /* support for \\P, \\p, and \\X has not been compiled */
496 case 167: /* this version of PCRE is not compiled with Unicode property support */
497 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
498 case 174: /* invalid UTF-16 string */
499 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
500 * and we do not check if strings are valid */
501 case 164: /* ] is an invalid data character in JavaScript compatibility mode */
502 /* This should not happen as we don't use PCRE_JAVASCRIPT_COMPAT */
503 g_warning ("%s", *errmsg);
504 *errcode = G_REGEX_ERROR_COMPILE;
506 case 170: /* internal error: unknown opcode in find_fixedlength() */
507 *errcode = G_REGEX_ERROR_INTERNAL;
511 *errcode = G_REGEX_ERROR_COMPILE;
518 match_info_new (const GRegex *regex,
525 GMatchInfo *match_info;
528 string_len = strlen (string);
530 match_info = g_new0 (GMatchInfo, 1);
531 match_info->ref_count = 1;
532 match_info->regex = g_regex_ref ((GRegex *)regex);
533 match_info->string = string;
534 match_info->string_len = string_len;
535 match_info->matches = PCRE_ERROR_NOMATCH;
536 match_info->pos = start_position;
537 match_info->match_opts = match_options;
541 /* These values should be enough for most cases, if they are not
542 * enough g_regex_match_all_full() will expand them. */
543 match_info->n_offsets = 24;
544 match_info->n_workspace = 100;
545 match_info->workspace = g_new (gint, match_info->n_workspace);
550 pcre_fullinfo (regex->pcre_re, regex->extra,
551 PCRE_INFO_CAPTURECOUNT, &capture_count);
552 match_info->n_offsets = (capture_count + 1) * 3;
555 match_info->offsets = g_new0 (gint, match_info->n_offsets);
556 /* Set an invalid position for the previous match. */
557 match_info->offsets[0] = -1;
558 match_info->offsets[1] = -1;
564 * g_match_info_get_regex:
565 * @match_info: a #GMatchInfo
567 * Returns #GRegex object used in @match_info. It belongs to Glib
568 * and must not be freed. Use g_regex_ref() if you need to keep it
569 * after you free @match_info object.
571 * Returns: #GRegex object used in @match_info
576 g_match_info_get_regex (const GMatchInfo *match_info)
578 g_return_val_if_fail (match_info != NULL, NULL);
579 return match_info->regex;
583 * g_match_info_get_string:
584 * @match_info: a #GMatchInfo
586 * Returns the string searched with @match_info. This is the
587 * string passed to g_regex_match() or g_regex_replace() so
588 * you may not free it before calling this function.
590 * Returns: the string searched with @match_info
595 g_match_info_get_string (const GMatchInfo *match_info)
597 g_return_val_if_fail (match_info != NULL, NULL);
598 return match_info->string;
603 * @match_info: a #GMatchInfo
605 * Increases reference count of @match_info by 1.
607 * Returns: @match_info
612 g_match_info_ref (GMatchInfo *match_info)
614 g_return_val_if_fail (match_info != NULL, NULL);
615 g_atomic_int_inc (&match_info->ref_count);
620 * g_match_info_unref:
621 * @match_info: a #GMatchInfo
623 * Decreases reference count of @match_info by 1. When reference count drops
624 * to zero, it frees all the memory associated with the match_info structure.
629 g_match_info_unref (GMatchInfo *match_info)
631 if (g_atomic_int_dec_and_test (&match_info->ref_count))
633 g_regex_unref (match_info->regex);
634 g_free (match_info->offsets);
635 g_free (match_info->workspace);
642 * @match_info: (allow-none): a #GMatchInfo, or %NULL
644 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
650 g_match_info_free (GMatchInfo *match_info)
652 if (match_info == NULL)
655 g_match_info_unref (match_info);
660 * @match_info: a #GMatchInfo structure
661 * @error: location to store the error occurring, or %NULL to ignore errors
663 * Scans for the next match using the same parameters of the previous
664 * call to g_regex_match_full() or g_regex_match() that returned
667 * The match is done on the string passed to the match function, so you
668 * cannot free it before calling this function.
670 * Returns: %TRUE is the string matched, %FALSE otherwise
675 g_match_info_next (GMatchInfo *match_info,
678 gint prev_match_start;
681 g_return_val_if_fail (match_info != NULL, FALSE);
682 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
683 g_return_val_if_fail (match_info->pos >= 0, FALSE);
685 prev_match_start = match_info->offsets[0];
686 prev_match_end = match_info->offsets[1];
688 if (match_info->pos > match_info->string_len)
690 /* we have reached the end of the string */
691 match_info->pos = -1;
692 match_info->matches = PCRE_ERROR_NOMATCH;
696 match_info->matches = pcre_exec (match_info->regex->pcre_re,
697 match_info->regex->extra,
699 match_info->string_len,
701 match_info->regex->match_opts | match_info->match_opts,
703 match_info->n_offsets);
704 if (IS_PCRE_ERROR (match_info->matches))
706 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
707 _("Error while matching regular expression %s: %s"),
708 match_info->regex->pattern, match_error (match_info->matches));
712 /* avoid infinite loops if the pattern is an empty string or something
714 if (match_info->pos == match_info->offsets[1])
716 if (match_info->pos > match_info->string_len)
718 /* we have reached the end of the string */
719 match_info->pos = -1;
720 match_info->matches = PCRE_ERROR_NOMATCH;
724 match_info->pos = NEXT_CHAR (match_info->regex,
725 &match_info->string[match_info->pos]) -
730 match_info->pos = match_info->offsets[1];
733 /* it's possible to get two identical matches when we are matching
734 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
735 * the string is "RegExTest" we have:
736 * - search at position 0: match from 0 to 0
737 * - search at position 1: match from 3 to 3
738 * - search at position 3: match from 3 to 3 (duplicate)
739 * - search at position 4: match from 5 to 5
740 * - search at position 5: match from 5 to 5 (duplicate)
741 * - search at position 6: no match -> stop
742 * so we have to ignore the duplicates.
743 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
744 if (match_info->matches >= 0 &&
745 prev_match_start == match_info->offsets[0] &&
746 prev_match_end == match_info->offsets[1])
748 /* ignore this match and search the next one */
749 return g_match_info_next (match_info, error);
752 return match_info->matches >= 0;
756 * g_match_info_matches:
757 * @match_info: a #GMatchInfo structure
759 * Returns whether the previous match operation succeeded.
761 * Returns: %TRUE if the previous match operation succeeded,
767 g_match_info_matches (const GMatchInfo *match_info)
769 g_return_val_if_fail (match_info != NULL, FALSE);
771 return match_info->matches >= 0;
775 * g_match_info_get_match_count:
776 * @match_info: a #GMatchInfo structure
778 * Retrieves the number of matched substrings (including substring 0,
779 * that is the whole matched text), so 1 is returned if the pattern
780 * has no substrings in it and 0 is returned if the match failed.
782 * If the last match was obtained using the DFA algorithm, that is
783 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
784 * count is not that of the number of capturing parentheses but that of
785 * the number of matched substrings.
787 * Returns: Number of matched substrings, or -1 if an error occurred
792 g_match_info_get_match_count (const GMatchInfo *match_info)
794 g_return_val_if_fail (match_info, -1);
796 if (match_info->matches == PCRE_ERROR_NOMATCH)
799 else if (match_info->matches < PCRE_ERROR_NOMATCH)
804 return match_info->matches;
808 * g_match_info_is_partial_match:
809 * @match_info: a #GMatchInfo structure
811 * Usually if the string passed to g_regex_match*() matches as far as
812 * it goes, but is too short to match the entire pattern, %FALSE is
813 * returned. There are circumstances where it might be helpful to
814 * distinguish this case from other cases in which there is no match.
816 * Consider, for example, an application where a human is required to
817 * type in data for a field with specific formatting requirements. An
818 * example might be a date in the form ddmmmyy, defined by the pattern
819 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
820 * If the application sees the user’s keystrokes one by one, and can
821 * check that what has been typed so far is potentially valid, it is
822 * able to raise an error as soon as a mistake is made.
824 * GRegex supports the concept of partial matching by means of the
825 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
826 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
827 * for a complete match, %FALSE otherwise. But, when these functions
828 * return %FALSE, you can check if the match was partial calling
829 * g_match_info_is_partial_match().
831 * When using partial matching you cannot use g_match_info_fetch*().
833 * Because of the way certain internal optimizations are implemented
834 * the partial matching algorithm cannot be used with all patterns.
835 * So repeated single characters such as "a{2,4}" and repeated single
836 * meta-sequences such as "\d+" are not permitted if the maximum number
837 * of occurrences is greater than one. Optional items such as "\d?"
838 * (where the maximum is one) are permitted. Quantifiers with any values
839 * are permitted after parentheses, so the invalid examples above can be
840 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
841 * for a pattern that does not conform to the restrictions, matching
842 * functions return an error.
844 * Returns: %TRUE if the match was partial, %FALSE otherwise
849 g_match_info_is_partial_match (const GMatchInfo *match_info)
851 g_return_val_if_fail (match_info != NULL, FALSE);
853 return match_info->matches == PCRE_ERROR_PARTIAL;
857 * g_match_info_expand_references:
858 * @match_info: (allow-none): a #GMatchInfo or %NULL
859 * @string_to_expand: the string to expand
860 * @error: location to store the error occurring, or %NULL to ignore errors
862 * Returns a new string containing the text in @string_to_expand with
863 * references and escape sequences expanded. References refer to the last
864 * match done with @string against @regex and have the same syntax used by
867 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
868 * passed to g_regex_new().
870 * The backreferences are extracted from the string passed to the match
871 * function, so you cannot call this function after freeing the string.
873 * @match_info may be %NULL in which case @string_to_expand must not
874 * contain references. For instance "foo\n" does not refer to an actual
875 * pattern and '\n' merely will be replaced with \n character,
876 * while to expand "\0" (whole match) one needs the result of a match.
877 * Use g_regex_check_replacement() to find out whether @string_to_expand
878 * contains references.
880 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
885 g_match_info_expand_references (const GMatchInfo *match_info,
886 const gchar *string_to_expand,
891 GError *tmp_error = NULL;
893 g_return_val_if_fail (string_to_expand != NULL, NULL);
894 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
896 list = split_replacement (string_to_expand, &tmp_error);
897 if (tmp_error != NULL)
899 g_propagate_error (error, tmp_error);
903 if (!match_info && interpolation_list_needs_match (list))
905 g_critical ("String '%s' contains references to the match, can't "
906 "expand references without GMatchInfo object",
911 result = g_string_sized_new (strlen (string_to_expand));
912 interpolate_replacement (match_info, result, list);
914 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
916 return g_string_free (result, FALSE);
920 * g_match_info_fetch:
921 * @match_info: #GMatchInfo structure
922 * @match_num: number of the sub expression
924 * Retrieves the text matching the @match_num<!-- -->'th capturing
925 * parentheses. 0 is the full text of the match, 1 is the first paren
926 * set, 2 the second, and so on.
928 * If @match_num is a valid sub pattern but it didn't match anything
929 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
930 * string is returned.
932 * If the match was obtained using the DFA algorithm, that is using
933 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
934 * string is not that of a set of parentheses but that of a matched
935 * substring. Substrings are matched in reverse order of length, so
936 * 0 is the longest match.
938 * The string is fetched from the string passed to the match function,
939 * so you cannot call this function after freeing the string.
941 * Returns: (allow-none): The matched substring, or %NULL if an error
942 * occurred. You have to free the string yourself
947 g_match_info_fetch (const GMatchInfo *match_info,
950 /* we cannot use pcre_get_substring() because it allocates the
951 * string using pcre_malloc(). */
955 g_return_val_if_fail (match_info != NULL, NULL);
956 g_return_val_if_fail (match_num >= 0, NULL);
958 /* match_num does not exist or it didn't matched, i.e. matching "b"
959 * against "(a)?b" then group 0 is empty. */
960 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
962 else if (start == -1)
963 match = g_strdup ("");
965 match = g_strndup (&match_info->string[start], end - start);
971 * g_match_info_fetch_pos:
972 * @match_info: #GMatchInfo structure
973 * @match_num: number of the sub expression
974 * @start_pos: (out) (allow-none): pointer to location where to store
975 * the start position, or %NULL
976 * @end_pos: (out) (allow-none): pointer to location where to store
977 * the end position, or %NULL
979 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
980 * parentheses. 0 is the full text of the match, 1 is the first
981 * paren set, 2 the second, and so on.
983 * If @match_num is a valid sub pattern but it didn't match anything
984 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
985 * and @end_pos are set to -1 and %TRUE is returned.
987 * If the match was obtained using the DFA algorithm, that is using
988 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
989 * position is not that of a set of parentheses but that of a matched
990 * substring. Substrings are matched in reverse order of length, so
991 * 0 is the longest match.
993 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
994 * the position cannot be fetched, @start_pos and @end_pos are left
1000 g_match_info_fetch_pos (const GMatchInfo *match_info,
1005 g_return_val_if_fail (match_info != NULL, FALSE);
1006 g_return_val_if_fail (match_num >= 0, FALSE);
1008 /* make sure the sub expression number they're requesting is less than
1009 * the total number of sub expressions that were matched. */
1010 if (match_num >= match_info->matches)
1013 if (start_pos != NULL)
1014 *start_pos = match_info->offsets[2 * match_num];
1016 if (end_pos != NULL)
1017 *end_pos = match_info->offsets[2 * match_num + 1];
1023 * Returns number of first matched subpattern with name @name.
1024 * There may be more than one in case when DUPNAMES is used,
1025 * and not all subpatterns with that name match;
1026 * pcre_get_stringnumber() does not work in that case.
1029 get_matched_substring_number (const GMatchInfo *match_info,
1033 gchar *first, *last;
1036 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
1037 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
1039 /* This code is copied from pcre_get.c: get_first_set() */
1040 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
1048 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
1050 gint n = (entry[0] << 8) + entry[1];
1051 if (match_info->offsets[n*2] >= 0)
1055 return (first[0] << 8) + first[1];
1059 * g_match_info_fetch_named:
1060 * @match_info: #GMatchInfo structure
1061 * @name: name of the subexpression
1063 * Retrieves the text matching the capturing parentheses named @name.
1065 * If @name is a valid sub pattern name but it didn't match anything
1066 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1067 * then an empty string is returned.
1069 * The string is fetched from the string passed to the match function,
1070 * so you cannot call this function after freeing the string.
1072 * Returns: (allow-none): The matched substring, or %NULL if an error
1073 * occurred. You have to free the string yourself
1078 g_match_info_fetch_named (const GMatchInfo *match_info,
1081 /* we cannot use pcre_get_named_substring() because it allocates the
1082 * string using pcre_malloc(). */
1085 g_return_val_if_fail (match_info != NULL, NULL);
1086 g_return_val_if_fail (name != NULL, NULL);
1088 num = get_matched_substring_number (match_info, name);
1092 return g_match_info_fetch (match_info, num);
1096 * g_match_info_fetch_named_pos:
1097 * @match_info: #GMatchInfo structure
1098 * @name: name of the subexpression
1099 * @start_pos: (out) (allow-none): pointer to location where to store
1100 * the start position, or %NULL
1101 * @end_pos: (out) (allow-none): pointer to location where to store
1102 * the end position, or %NULL
1104 * Retrieves the position in bytes of the capturing parentheses named @name.
1106 * If @name is a valid sub pattern name but it didn't match anything
1107 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1108 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1110 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1111 * If the position cannot be fetched, @start_pos and @end_pos
1112 * are left unchanged.
1117 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
1124 g_return_val_if_fail (match_info != NULL, FALSE);
1125 g_return_val_if_fail (name != NULL, FALSE);
1127 num = get_matched_substring_number (match_info, name);
1131 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
1135 * g_match_info_fetch_all:
1136 * @match_info: a #GMatchInfo structure
1138 * Bundles up pointers to each of the matching substrings from a match
1139 * and stores them in an array of gchar pointers. The first element in
1140 * the returned array is the match number 0, i.e. the entire matched
1143 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1144 * "b" against "(a)?b") then an empty string is inserted.
1146 * If the last match was obtained using the DFA algorithm, that is using
1147 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1148 * strings are not that matched by sets of parentheses but that of the
1149 * matched substring. Substrings are matched in reverse order of length,
1150 * so the first one is the longest match.
1152 * The strings are fetched from the string passed to the match function,
1153 * so you cannot call this function after freeing the string.
1155 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
1156 * It must be freed using g_strfreev(). If the previous match failed
1162 g_match_info_fetch_all (const GMatchInfo *match_info)
1164 /* we cannot use pcre_get_substring_list() because the returned value
1165 * isn't suitable for g_strfreev(). */
1169 g_return_val_if_fail (match_info != NULL, NULL);
1171 if (match_info->matches < 0)
1174 result = g_new (gchar *, match_info->matches + 1);
1175 for (i = 0; i < match_info->matches; i++)
1176 result[i] = g_match_info_fetch (match_info, i);
1186 g_regex_error_quark (void)
1188 static GQuark error_quark = 0;
1190 if (error_quark == 0)
1191 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1200 * Increases reference count of @regex by 1.
1207 g_regex_ref (GRegex *regex)
1209 g_return_val_if_fail (regex != NULL, NULL);
1210 g_atomic_int_inc (®ex->ref_count);
1218 * Decreases reference count of @regex by 1. When reference count drops
1219 * to zero, it frees all the memory associated with the regex structure.
1224 g_regex_unref (GRegex *regex)
1226 g_return_if_fail (regex != NULL);
1228 if (g_atomic_int_dec_and_test (®ex->ref_count))
1230 g_free (regex->pattern);
1231 if (regex->pcre_re != NULL)
1232 pcre_free (regex->pcre_re);
1233 if (regex->extra != NULL)
1234 pcre_free (regex->extra);
1241 * @pattern: the regular expression
1242 * @compile_options: compile options for the regular expression, or 0
1243 * @match_options: match options for the regular expression, or 0
1244 * @error: return location for a #GError
1246 * Compiles the regular expression to an internal form, and does
1247 * the initial setup of the #GRegex structure.
1249 * Returns: a #GRegex structure. Call g_regex_unref() when you
1255 g_regex_new (const gchar *pattern,
1256 GRegexCompileFlags compile_options,
1257 GRegexMatchFlags match_options,
1262 const gchar *errmsg;
1265 gboolean optimize = FALSE;
1266 static volatile gsize initialised = 0;
1267 unsigned long int pcre_compile_options;
1269 g_return_val_if_fail (pattern != NULL, NULL);
1270 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1271 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1272 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1274 if (g_once_init_enter (&initialised))
1276 int supports_utf8, supports_ucp;
1278 pcre_config (PCRE_CONFIG_UTF8, &supports_utf8);
1280 g_critical (_("PCRE library is compiled without UTF8 support"));
1282 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &supports_ucp);
1284 g_critical (_("PCRE library is compiled without UTF8 properties support"));
1286 g_once_init_leave (&initialised, supports_utf8 && supports_ucp ? 1 : 2);
1289 if (G_UNLIKELY (initialised != 1))
1291 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE,
1292 _("PCRE library is compiled with incompatible options"));
1296 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1297 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1298 if (compile_options & G_REGEX_OPTIMIZE)
1301 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1302 * instead uses UTF-8 only if required with PCRE_UTF8. */
1303 if (compile_options & G_REGEX_RAW)
1306 compile_options &= ~G_REGEX_RAW;
1311 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1312 match_options |= PCRE_NO_UTF8_CHECK;
1315 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1316 * not for the system one. */
1317 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1318 !(compile_options & G_REGEX_NEWLINE_LF))
1320 compile_options |= PCRE_NEWLINE_ANY;
1323 compile_options |= PCRE_UCP;
1325 /* PCRE_BSR_UNICODE is the default for the internal PCRE but
1326 * possibly not for the system one.
1328 if (~compile_options & G_REGEX_BSR_ANYCRLF)
1329 compile_options |= PCRE_BSR_UNICODE;
1331 /* compile the pattern */
1332 re = pcre_compile2 (pattern, compile_options, &errcode,
1333 &errmsg, &erroffset, NULL);
1335 /* if the compilation failed, set the error member and return
1341 /* Translate the PCRE error code to GRegexError and use a translated
1342 * error message if possible */
1343 translate_compile_error (&errcode, &errmsg);
1345 /* PCRE uses byte offsets but we want to show character offsets */
1346 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1348 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1349 _("Error while compiling regular "
1350 "expression %s at char %d: %s"),
1351 pattern, erroffset, errmsg);
1352 g_propagate_error (error, tmp_error);
1357 /* For options set at the beginning of the pattern, pcre puts them into
1358 * compile options, e.g. "(?i)foo" will make the pcre structure store
1359 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1360 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1361 compile_options = pcre_compile_options;
1363 if (!(compile_options & G_REGEX_DUPNAMES))
1365 gboolean jchanged = FALSE;
1366 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1368 compile_options |= G_REGEX_DUPNAMES;
1371 regex = g_new0 (GRegex, 1);
1372 regex->ref_count = 1;
1373 regex->pattern = g_strdup (pattern);
1374 regex->pcre_re = re;
1375 regex->compile_opts = compile_options;
1376 regex->match_opts = match_options;
1380 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1383 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1384 G_REGEX_ERROR_OPTIMIZE,
1385 _("Error while optimizing "
1386 "regular expression %s: %s"),
1389 g_propagate_error (error, tmp_error);
1391 g_regex_unref (regex);
1400 * g_regex_get_pattern:
1401 * @regex: a #GRegex structure
1403 * Gets the pattern string associated with @regex, i.e. a copy of
1404 * the string passed to g_regex_new().
1406 * Returns: the pattern of @regex
1411 g_regex_get_pattern (const GRegex *regex)
1413 g_return_val_if_fail (regex != NULL, NULL);
1415 return regex->pattern;
1419 * g_regex_get_max_backref:
1422 * Returns the number of the highest back reference
1423 * in the pattern, or 0 if the pattern does not contain
1426 * Returns: the number of the highest back reference
1431 g_regex_get_max_backref (const GRegex *regex)
1435 pcre_fullinfo (regex->pcre_re, regex->extra,
1436 PCRE_INFO_BACKREFMAX, &value);
1442 * g_regex_get_capture_count:
1445 * Returns the number of capturing subpatterns in the pattern.
1447 * Returns: the number of capturing subpatterns
1452 g_regex_get_capture_count (const GRegex *regex)
1456 pcre_fullinfo (regex->pcre_re, regex->extra,
1457 PCRE_INFO_CAPTURECOUNT, &value);
1463 * g_regex_get_has_cr_or_lf:
1464 * @regex: a #GRegex structure
1466 * Checks whether the pattern contains explicit CR or LF references.
1468 * Returns: %TRUE if the pattern contains explicit CR or LF references
1473 g_regex_get_has_cr_or_lf (const GRegex *regex)
1477 pcre_fullinfo (regex->pcre_re, regex->extra,
1478 PCRE_INFO_HASCRORLF, &value);
1484 * g_regex_get_compile_flags:
1487 * Returns the compile options that @regex was created with.
1489 * Returns: flags from #GRegexCompileFlags
1494 g_regex_get_compile_flags (const GRegex *regex)
1496 g_return_val_if_fail (regex != NULL, 0);
1498 return regex->compile_opts;
1502 * g_regex_get_match_flags:
1505 * Returns the match options that @regex was created with.
1507 * Returns: flags from #GRegexMatchFlags
1512 g_regex_get_match_flags (const GRegex *regex)
1514 g_return_val_if_fail (regex != NULL, 0);
1516 return regex->match_opts;
1520 * g_regex_match_simple:
1521 * @pattern: the regular expression
1522 * @string: the string to scan for matches
1523 * @compile_options: compile options for the regular expression, or 0
1524 * @match_options: match options, or 0
1526 * Scans for a match in @string for @pattern.
1528 * This function is equivalent to g_regex_match() but it does not
1529 * require to compile the pattern with g_regex_new(), avoiding some
1530 * lines of code when you need just to do a match without extracting
1531 * substrings, capture counts, and so on.
1533 * If this function is to be called on the same @pattern more than
1534 * once, it's more efficient to compile the pattern once with
1535 * g_regex_new() and then use g_regex_match().
1537 * Returns: %TRUE if the string matched, %FALSE otherwise
1542 g_regex_match_simple (const gchar *pattern,
1543 const gchar *string,
1544 GRegexCompileFlags compile_options,
1545 GRegexMatchFlags match_options)
1550 regex = g_regex_new (pattern, compile_options, 0, NULL);
1553 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1554 g_regex_unref (regex);
1560 * @regex: a #GRegex structure from g_regex_new()
1561 * @string: the string to scan for matches
1562 * @match_options: match options
1563 * @match_info: (out) (allow-none): pointer to location where to store
1564 * the #GMatchInfo, or %NULL if you do not need it
1566 * Scans for a match in string for the pattern in @regex.
1567 * The @match_options are combined with the match options specified
1568 * when the @regex structure was created, letting you have more
1569 * flexibility in reusing #GRegex structures.
1571 * A #GMatchInfo structure, used to get information on the match,
1572 * is stored in @match_info if not %NULL. Note that if @match_info
1573 * is not %NULL then it is created even if the function returns %FALSE,
1574 * i.e. you must free it regardless if regular expression actually matched.
1576 * To retrieve all the non-overlapping matches of the pattern in
1577 * string you can use g_match_info_next().
1581 * print_uppercase_words (const gchar *string)
1583 * /* Print all uppercase-only words. */
1585 * GMatchInfo *match_info;
1587 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1588 * g_regex_match (regex, string, 0, &match_info);
1589 * while (g_match_info_matches (match_info))
1591 * gchar *word = g_match_info_fetch (match_info, 0);
1592 * g_print ("Found: %s\n", word);
1594 * g_match_info_next (match_info, NULL);
1596 * g_match_info_free (match_info);
1597 * g_regex_unref (regex);
1601 * @string is not copied and is used in #GMatchInfo internally. If
1602 * you use any #GMatchInfo method (except g_match_info_free()) after
1603 * freeing or modifying @string then the behaviour is undefined.
1605 * Returns: %TRUE is the string matched, %FALSE otherwise
1610 g_regex_match (const GRegex *regex,
1611 const gchar *string,
1612 GRegexMatchFlags match_options,
1613 GMatchInfo **match_info)
1615 return g_regex_match_full (regex, string, -1, 0, match_options,
1620 * g_regex_match_full:
1621 * @regex: a #GRegex structure from g_regex_new()
1622 * @string: (array length=string_len): the string to scan for matches
1623 * @string_len: the length of @string, or -1 if @string is nul-terminated
1624 * @start_position: starting index of the string to match
1625 * @match_options: match options
1626 * @match_info: (out) (allow-none): pointer to location where to store
1627 * the #GMatchInfo, or %NULL if you do not need it
1628 * @error: location to store the error occurring, or %NULL to ignore errors
1630 * Scans for a match in string for the pattern in @regex.
1631 * The @match_options are combined with the match options specified
1632 * when the @regex structure was created, letting you have more
1633 * flexibility in reusing #GRegex structures.
1635 * Setting @start_position differs from just passing over a shortened
1636 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1637 * that begins with any kind of lookbehind assertion, such as "\b".
1639 * A #GMatchInfo structure, used to get information on the match, is
1640 * stored in @match_info if not %NULL. Note that if @match_info is
1641 * not %NULL then it is created even if the function returns %FALSE,
1642 * i.e. you must free it regardless if regular expression actually
1645 * @string is not copied and is used in #GMatchInfo internally. If
1646 * you use any #GMatchInfo method (except g_match_info_free()) after
1647 * freeing or modifying @string then the behaviour is undefined.
1649 * To retrieve all the non-overlapping matches of the pattern in
1650 * string you can use g_match_info_next().
1654 * print_uppercase_words (const gchar *string)
1656 * /* Print all uppercase-only words. */
1658 * GMatchInfo *match_info;
1659 * GError *error = NULL;
1661 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1662 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1663 * while (g_match_info_matches (match_info))
1665 * gchar *word = g_match_info_fetch (match_info, 0);
1666 * g_print ("Found: %s\n", word);
1668 * g_match_info_next (match_info, &error);
1670 * g_match_info_free (match_info);
1671 * g_regex_unref (regex);
1672 * if (error != NULL)
1674 * g_printerr ("Error while matching: %s\n", error->message);
1675 * g_error_free (error);
1680 * Returns: %TRUE is the string matched, %FALSE otherwise
1685 g_regex_match_full (const GRegex *regex,
1686 const gchar *string,
1688 gint start_position,
1689 GRegexMatchFlags match_options,
1690 GMatchInfo **match_info,
1696 g_return_val_if_fail (regex != NULL, FALSE);
1697 g_return_val_if_fail (string != NULL, FALSE);
1698 g_return_val_if_fail (start_position >= 0, FALSE);
1699 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1700 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1702 info = match_info_new (regex, string, string_len, start_position,
1703 match_options, FALSE);
1704 match_ok = g_match_info_next (info, error);
1705 if (match_info != NULL)
1708 g_match_info_free (info);
1714 * g_regex_match_all:
1715 * @regex: a #GRegex structure from g_regex_new()
1716 * @string: the string to scan for matches
1717 * @match_options: match options
1718 * @match_info: (out) (allow-none): pointer to location where to store
1719 * the #GMatchInfo, or %NULL if you do not need it
1721 * Using the standard algorithm for regular expression matching only
1722 * the longest match in the string is retrieved. This function uses
1723 * a different algorithm so it can retrieve all the possible matches.
1724 * For more documentation see g_regex_match_all_full().
1726 * A #GMatchInfo structure, used to get information on the match, is
1727 * stored in @match_info if not %NULL. Note that if @match_info is
1728 * not %NULL then it is created even if the function returns %FALSE,
1729 * i.e. you must free it regardless if regular expression actually
1732 * @string is not copied and is used in #GMatchInfo internally. If
1733 * you use any #GMatchInfo method (except g_match_info_free()) after
1734 * freeing or modifying @string then the behaviour is undefined.
1736 * Returns: %TRUE is the string matched, %FALSE otherwise
1741 g_regex_match_all (const GRegex *regex,
1742 const gchar *string,
1743 GRegexMatchFlags match_options,
1744 GMatchInfo **match_info)
1746 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1751 * g_regex_match_all_full:
1752 * @regex: a #GRegex structure from g_regex_new()
1753 * @string: (array length=string_len): the string to scan for matches
1754 * @string_len: the length of @string, or -1 if @string is nul-terminated
1755 * @start_position: starting index of the string to match
1756 * @match_options: match options
1757 * @match_info: (out) (allow-none): pointer to location where to store
1758 * the #GMatchInfo, or %NULL if you do not need it
1759 * @error: location to store the error occurring, or %NULL to ignore errors
1761 * Using the standard algorithm for regular expression matching only
1762 * the longest match in the string is retrieved, it is not possible
1763 * to obtain all the available matches. For instance matching
1764 * "<a> <b> <c>" against the pattern "<.*>"
1765 * you get "<a> <b> <c>".
1767 * This function uses a different algorithm (called DFA, i.e. deterministic
1768 * finite automaton), so it can retrieve all the possible matches, all
1769 * starting at the same point in the string. For instance matching
1770 * "<a> <b> <c>" against the pattern "<.*>"
1771 * you would obtain three matches: "<a> <b> <c>",
1772 * "<a> <b>" and "<a>".
1774 * The number of matched strings is retrieved using
1775 * g_match_info_get_match_count(). To obtain the matched strings and
1776 * their position you can use, respectively, g_match_info_fetch() and
1777 * g_match_info_fetch_pos(). Note that the strings are returned in
1778 * reverse order of length; that is, the longest matching string is
1781 * Note that the DFA algorithm is slower than the standard one and it
1782 * is not able to capture substrings, so backreferences do not work.
1784 * Setting @start_position differs from just passing over a shortened
1785 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1786 * that begins with any kind of lookbehind assertion, such as "\b".
1788 * A #GMatchInfo structure, used to get information on the match, is
1789 * stored in @match_info if not %NULL. Note that if @match_info is
1790 * not %NULL then it is created even if the function returns %FALSE,
1791 * i.e. you must free it regardless if regular expression actually
1794 * @string is not copied and is used in #GMatchInfo internally. If
1795 * you use any #GMatchInfo method (except g_match_info_free()) after
1796 * freeing or modifying @string then the behaviour is undefined.
1798 * Returns: %TRUE is the string matched, %FALSE otherwise
1803 g_regex_match_all_full (const GRegex *regex,
1804 const gchar *string,
1806 gint start_position,
1807 GRegexMatchFlags match_options,
1808 GMatchInfo **match_info,
1814 g_return_val_if_fail (regex != NULL, FALSE);
1815 g_return_val_if_fail (string != NULL, FALSE);
1816 g_return_val_if_fail (start_position >= 0, FALSE);
1817 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1818 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1820 info = match_info_new (regex, string, string_len, start_position,
1821 match_options, TRUE);
1827 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1828 info->string, info->string_len,
1830 regex->match_opts | match_options,
1831 info->offsets, info->n_offsets,
1832 info->workspace, info->n_workspace);
1833 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1835 /* info->workspace is too small. */
1836 info->n_workspace *= 2;
1837 info->workspace = g_realloc (info->workspace,
1838 info->n_workspace * sizeof (gint));
1841 else if (info->matches == 0)
1843 /* info->offsets is too small. */
1844 info->n_offsets *= 2;
1845 info->offsets = g_realloc (info->offsets,
1846 info->n_offsets * sizeof (gint));
1849 else if (IS_PCRE_ERROR (info->matches))
1851 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1852 _("Error while matching regular expression %s: %s"),
1853 regex->pattern, match_error (info->matches));
1857 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1860 if (match_info != NULL)
1863 g_match_info_free (info);
1865 return info->matches >= 0;
1869 * g_regex_get_string_number:
1870 * @regex: #GRegex structure
1871 * @name: name of the subexpression
1873 * Retrieves the number of the subexpression named @name.
1875 * Returns: The number of the subexpression or -1 if @name
1881 g_regex_get_string_number (const GRegex *regex,
1886 g_return_val_if_fail (regex != NULL, -1);
1887 g_return_val_if_fail (name != NULL, -1);
1889 num = pcre_get_stringnumber (regex->pcre_re, name);
1890 if (num == PCRE_ERROR_NOSUBSTRING)
1897 * g_regex_split_simple:
1898 * @pattern: the regular expression
1899 * @string: the string to scan for matches
1900 * @compile_options: compile options for the regular expression, or 0
1901 * @match_options: match options, or 0
1903 * Breaks the string on the pattern, and returns an array of
1904 * the tokens. If the pattern contains capturing parentheses,
1905 * then the text for each of the substrings will also be returned.
1906 * If the pattern does not match anywhere in the string, then the
1907 * whole string is returned as the first token.
1909 * This function is equivalent to g_regex_split() but it does
1910 * not require to compile the pattern with g_regex_new(), avoiding
1911 * some lines of code when you need just to do a split without
1912 * extracting substrings, capture counts, and so on.
1914 * If this function is to be called on the same @pattern more than
1915 * once, it's more efficient to compile the pattern once with
1916 * g_regex_new() and then use g_regex_split().
1918 * As a special case, the result of splitting the empty string ""
1919 * is an empty vector, not a vector containing a single string.
1920 * The reason for this special case is that being able to represent
1921 * a empty vector is typically more useful than consistent handling
1922 * of empty elements. If you do need to represent empty elements,
1923 * you'll need to check for the empty string before calling this
1926 * A pattern that can match empty strings splits @string into
1927 * separate characters wherever it matches the empty string between
1928 * characters. For example splitting "ab c" using as a separator
1929 * "\s*", you will get "a", "b" and "c".
1931 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1936 g_regex_split_simple (const gchar *pattern,
1937 const gchar *string,
1938 GRegexCompileFlags compile_options,
1939 GRegexMatchFlags match_options)
1944 regex = g_regex_new (pattern, compile_options, 0, NULL);
1948 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1949 g_regex_unref (regex);
1955 * @regex: a #GRegex structure
1956 * @string: the string to split with the pattern
1957 * @match_options: match time option flags
1959 * Breaks the string on the pattern, and returns an array of the tokens.
1960 * If the pattern contains capturing parentheses, then the text for each
1961 * of the substrings will also be returned. If the pattern does not match
1962 * anywhere in the string, then the whole string is returned as the first
1965 * As a special case, the result of splitting the empty string "" is an
1966 * empty vector, not a vector containing a single string. The reason for
1967 * this special case is that being able to represent a empty vector is
1968 * typically more useful than consistent handling of empty elements. If
1969 * you do need to represent empty elements, you'll need to check for the
1970 * empty string before calling this function.
1972 * A pattern that can match empty strings splits @string into separate
1973 * characters wherever it matches the empty string between characters.
1974 * For example splitting "ab c" using as a separator "\s*", you will get
1977 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1982 g_regex_split (const GRegex *regex,
1983 const gchar *string,
1984 GRegexMatchFlags match_options)
1986 return g_regex_split_full (regex, string, -1, 0,
1987 match_options, 0, NULL);
1991 * g_regex_split_full:
1992 * @regex: a #GRegex structure
1993 * @string: (array length=string_len): the string to split with the pattern
1994 * @string_len: the length of @string, or -1 if @string is nul-terminated
1995 * @start_position: starting index of the string to match
1996 * @match_options: match time option flags
1997 * @max_tokens: the maximum number of tokens to split @string into.
1998 * If this is less than 1, the string is split completely
1999 * @error: return location for a #GError
2001 * Breaks the string on the pattern, and returns an array of the tokens.
2002 * If the pattern contains capturing parentheses, then the text for each
2003 * of the substrings will also be returned. If the pattern does not match
2004 * anywhere in the string, then the whole string is returned as the first
2007 * As a special case, the result of splitting the empty string "" is an
2008 * empty vector, not a vector containing a single string. The reason for
2009 * this special case is that being able to represent a empty vector is
2010 * typically more useful than consistent handling of empty elements. If
2011 * you do need to represent empty elements, you'll need to check for the
2012 * empty string before calling this function.
2014 * A pattern that can match empty strings splits @string into separate
2015 * characters wherever it matches the empty string between characters.
2016 * For example splitting "ab c" using as a separator "\s*", you will get
2019 * Setting @start_position differs from just passing over a shortened
2020 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2021 * that begins with any kind of lookbehind assertion, such as "\b".
2023 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2028 g_regex_split_full (const GRegex *regex,
2029 const gchar *string,
2031 gint start_position,
2032 GRegexMatchFlags match_options,
2036 GError *tmp_error = NULL;
2037 GMatchInfo *match_info;
2042 /* position of the last separator. */
2043 gint last_separator_end;
2044 /* was the last match 0 bytes long? */
2045 gboolean last_match_is_empty;
2046 /* the returned array of char **s */
2047 gchar **string_list;
2049 g_return_val_if_fail (regex != NULL, NULL);
2050 g_return_val_if_fail (string != NULL, NULL);
2051 g_return_val_if_fail (start_position >= 0, NULL);
2052 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2053 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2055 if (max_tokens <= 0)
2056 max_tokens = G_MAXINT;
2059 string_len = strlen (string);
2061 /* zero-length string */
2062 if (string_len - start_position == 0)
2063 return g_new0 (gchar *, 1);
2065 if (max_tokens == 1)
2067 string_list = g_new0 (gchar *, 2);
2068 string_list[0] = g_strndup (&string[start_position],
2069 string_len - start_position);
2075 last_separator_end = start_position;
2076 last_match_is_empty = FALSE;
2078 match_ok = g_regex_match_full (regex, string, string_len, start_position,
2079 match_options, &match_info, &tmp_error);
2081 while (tmp_error == NULL)
2085 last_match_is_empty =
2086 (match_info->offsets[0] == match_info->offsets[1]);
2088 /* we need to skip empty separators at the same position of the end
2089 * of another separator. e.g. the string is "a b" and the separator
2090 * is " *", so from 1 to 2 we have a match and at position 2 we have
2091 * an empty match. */
2092 if (last_separator_end != match_info->offsets[1])
2097 token = g_strndup (string + last_separator_end,
2098 match_info->offsets[0] - last_separator_end);
2099 list = g_list_prepend (list, token);
2102 /* if there were substrings, these need to be added to
2104 match_count = g_match_info_get_match_count (match_info);
2105 if (match_count > 1)
2107 for (i = 1; i < match_count; i++)
2108 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
2114 /* if there was no match, copy to end of string. */
2115 if (!last_match_is_empty)
2117 gchar *token = g_strndup (string + last_separator_end,
2118 match_info->string_len - last_separator_end);
2119 list = g_list_prepend (list, token);
2121 /* no more tokens, end the loop. */
2125 /* -1 to leave room for the last part. */
2126 if (token_count >= max_tokens - 1)
2128 /* we have reached the maximum number of tokens, so we copy
2129 * the remaining part of the string. */
2130 if (last_match_is_empty)
2132 /* the last match was empty, so we have moved one char
2133 * after the real position to avoid empty matches at the
2135 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
2137 /* the if is needed in the case we have terminated the available
2138 * tokens, but we are at the end of the string, so there are no
2139 * characters left to copy. */
2140 if (string_len > match_info->pos)
2142 gchar *token = g_strndup (string + match_info->pos,
2143 string_len - match_info->pos);
2144 list = g_list_prepend (list, token);
2150 last_separator_end = match_info->pos;
2151 if (last_match_is_empty)
2152 /* if the last match was empty, g_match_info_next() has moved
2153 * forward to avoid infinite loops, but we still need to copy that
2155 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
2157 match_ok = g_match_info_next (match_info, &tmp_error);
2159 g_match_info_free (match_info);
2160 if (tmp_error != NULL)
2162 g_propagate_error (error, tmp_error);
2163 g_list_free_full (list, g_free);
2164 match_info->pos = -1;
2168 string_list = g_new (gchar *, g_list_length (list) + 1);
2170 for (last = g_list_last (list); last; last = g_list_previous (last))
2171 string_list[i++] = last->data;
2172 string_list[i] = NULL;
2181 REPL_TYPE_CHARACTER,
2182 REPL_TYPE_SYMBOLIC_REFERENCE,
2183 REPL_TYPE_NUMERIC_REFERENCE,
2184 REPL_TYPE_CHANGE_CASE
2189 CHANGE_CASE_NONE = 1 << 0,
2190 CHANGE_CASE_UPPER = 1 << 1,
2191 CHANGE_CASE_LOWER = 1 << 2,
2192 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
2193 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
2194 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
2195 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
2196 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
2199 struct _InterpolationData
2205 ChangeCase change_case;
2209 free_interpolation_data (InterpolationData *data)
2211 g_free (data->text);
2215 static const gchar *
2216 expand_escape (const gchar *replacement,
2218 InterpolationData *data,
2223 const gchar *error_detail;
2225 GError *tmp_error = NULL;
2233 data->type = REPL_TYPE_CHARACTER;
2238 data->type = REPL_TYPE_CHARACTER;
2243 data->type = REPL_TYPE_CHARACTER;
2248 data->type = REPL_TYPE_CHARACTER;
2253 data->type = REPL_TYPE_CHARACTER;
2258 data->type = REPL_TYPE_CHARACTER;
2263 data->type = REPL_TYPE_CHARACTER;
2268 data->type = REPL_TYPE_CHARACTER;
2278 h = g_ascii_xdigit_value (*p);
2281 error_detail = _("hexadecimal digit or '}' expected");
2292 for (i = 0; i < 2; i++)
2294 h = g_ascii_xdigit_value (*p);
2297 error_detail = _("hexadecimal digit expected");
2304 data->type = REPL_TYPE_STRING;
2305 data->text = g_new0 (gchar, 8);
2306 g_unichar_to_utf8 (x, data->text);
2310 data->type = REPL_TYPE_CHANGE_CASE;
2311 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2315 data->type = REPL_TYPE_CHANGE_CASE;
2316 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2320 data->type = REPL_TYPE_CHANGE_CASE;
2321 data->change_case = CHANGE_CASE_LOWER;
2325 data->type = REPL_TYPE_CHANGE_CASE;
2326 data->change_case = CHANGE_CASE_UPPER;
2330 data->type = REPL_TYPE_CHANGE_CASE;
2331 data->change_case = CHANGE_CASE_NONE;
2337 error_detail = _("missing '<' in symbolic reference");
2346 error_detail = _("unfinished symbolic reference");
2353 error_detail = _("zero-length symbolic reference");
2356 if (g_ascii_isdigit (*q))
2361 h = g_ascii_digit_value (*q);
2364 error_detail = _("digit expected");
2373 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2380 if (!g_ascii_isalnum (*r))
2382 error_detail = _("illegal symbolic reference");
2389 data->text = g_strndup (q, p - q);
2390 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2395 /* if \0 is followed by a number is an octal number representing a
2396 * character, else it is a numeric reference. */
2397 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2400 p = g_utf8_next_char (p);
2413 for (i = 0; i < 3; i++)
2415 h = g_ascii_digit_value (*p);
2425 if (i == 2 && base == 10)
2431 if (base == 8 || i == 3)
2433 data->type = REPL_TYPE_STRING;
2434 data->text = g_new0 (gchar, 8);
2435 g_unichar_to_utf8 (x, data->text);
2439 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2444 error_detail = _("stray final '\\'");
2448 error_detail = _("unknown escape sequence");
2455 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2456 tmp_error = g_error_new (G_REGEX_ERROR,
2457 G_REGEX_ERROR_REPLACE,
2458 _("Error while parsing replacement "
2459 "text \"%s\" at char %lu: %s"),
2461 (gulong)(p - replacement),
2463 g_propagate_error (error, tmp_error);
2469 split_replacement (const gchar *replacement,
2473 InterpolationData *data;
2474 const gchar *p, *start;
2476 start = p = replacement;
2481 data = g_new0 (InterpolationData, 1);
2482 start = p = expand_escape (replacement, p, data, error);
2485 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2486 free_interpolation_data (data);
2490 list = g_list_prepend (list, data);
2495 if (*p == '\\' || *p == '\0')
2499 data = g_new0 (InterpolationData, 1);
2500 data->text = g_strndup (start, p - start);
2501 data->type = REPL_TYPE_STRING;
2502 list = g_list_prepend (list, data);
2508 return g_list_reverse (list);
2511 /* Change the case of c based on change_case. */
2512 #define CHANGE_CASE(c, change_case) \
2513 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2514 g_unichar_tolower (c) : \
2515 g_unichar_toupper (c))
2518 string_append (GString *string,
2520 ChangeCase *change_case)
2524 if (text[0] == '\0')
2527 if (*change_case == CHANGE_CASE_NONE)
2529 g_string_append (string, text);
2531 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2533 c = g_utf8_get_char (text);
2534 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2535 g_string_append (string, g_utf8_next_char (text));
2536 *change_case = CHANGE_CASE_NONE;
2540 while (*text != '\0')
2542 c = g_utf8_get_char (text);
2543 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2544 text = g_utf8_next_char (text);
2550 interpolate_replacement (const GMatchInfo *match_info,
2555 InterpolationData *idata;
2557 ChangeCase change_case = CHANGE_CASE_NONE;
2559 for (list = data; list; list = list->next)
2562 switch (idata->type)
2564 case REPL_TYPE_STRING:
2565 string_append (result, idata->text, &change_case);
2567 case REPL_TYPE_CHARACTER:
2568 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2569 if (change_case & CHANGE_CASE_SINGLE_MASK)
2570 change_case = CHANGE_CASE_NONE;
2572 case REPL_TYPE_NUMERIC_REFERENCE:
2573 match = g_match_info_fetch (match_info, idata->num);
2576 string_append (result, match, &change_case);
2580 case REPL_TYPE_SYMBOLIC_REFERENCE:
2581 match = g_match_info_fetch_named (match_info, idata->text);
2584 string_append (result, match, &change_case);
2588 case REPL_TYPE_CHANGE_CASE:
2589 change_case = idata->change_case;
2597 /* whether actual match_info is needed for replacement, i.e.
2598 * whether there are references
2601 interpolation_list_needs_match (GList *list)
2603 while (list != NULL)
2605 InterpolationData *data = list->data;
2607 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2608 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2621 * @regex: a #GRegex structure
2622 * @string: (array length=string_len): the string to perform matches against
2623 * @string_len: the length of @string, or -1 if @string is nul-terminated
2624 * @start_position: starting index of the string to match
2625 * @replacement: text to replace each match with
2626 * @match_options: options for the match
2627 * @error: location to store the error occurring, or %NULL to ignore errors
2629 * Replaces all occurrences of the pattern in @regex with the
2630 * replacement text. Backreferences of the form '\number' or
2631 * '\g<number>' in the replacement text are interpolated by the
2632 * number-th captured subexpression of the match, '\g<name>' refers
2633 * to the captured subexpression with the given name. '\0' refers to the
2634 * complete match, but '\0' followed by a number is the octal representation
2635 * of a character. To include a literal '\' in the replacement, write '\\'.
2636 * There are also escapes that changes the case of the following text:
2639 * <varlistentry><term>\l</term>
2641 * <para>Convert to lower case the next character</para>
2644 * <varlistentry><term>\u</term>
2646 * <para>Convert to upper case the next character</para>
2649 * <varlistentry><term>\L</term>
2651 * <para>Convert to lower case till \E</para>
2654 * <varlistentry><term>\U</term>
2656 * <para>Convert to upper case till \E</para>
2659 * <varlistentry><term>\E</term>
2661 * <para>End case modification</para>
2666 * If you do not need to use backreferences use g_regex_replace_literal().
2668 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2669 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2670 * you can use g_regex_replace_literal().
2672 * Setting @start_position differs from just passing over a shortened
2673 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2674 * begins with any kind of lookbehind assertion, such as "\b".
2676 * Returns: a newly allocated string containing the replacements
2681 g_regex_replace (const GRegex *regex,
2682 const gchar *string,
2684 gint start_position,
2685 const gchar *replacement,
2686 GRegexMatchFlags match_options,
2691 GError *tmp_error = NULL;
2693 g_return_val_if_fail (regex != NULL, NULL);
2694 g_return_val_if_fail (string != NULL, NULL);
2695 g_return_val_if_fail (start_position >= 0, NULL);
2696 g_return_val_if_fail (replacement != NULL, NULL);
2697 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2698 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2700 list = split_replacement (replacement, &tmp_error);
2701 if (tmp_error != NULL)
2703 g_propagate_error (error, tmp_error);
2707 result = g_regex_replace_eval (regex,
2708 string, string_len, start_position,
2710 interpolate_replacement,
2713 if (tmp_error != NULL)
2714 g_propagate_error (error, tmp_error);
2716 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2722 literal_replacement (const GMatchInfo *match_info,
2726 g_string_append (result, data);
2731 * g_regex_replace_literal:
2732 * @regex: a #GRegex structure
2733 * @string: (array length=string_len): the string to perform matches against
2734 * @string_len: the length of @string, or -1 if @string is nul-terminated
2735 * @start_position: starting index of the string to match
2736 * @replacement: text to replace each match with
2737 * @match_options: options for the match
2738 * @error: location to store the error occurring, or %NULL to ignore errors
2740 * Replaces all occurrences of the pattern in @regex with the
2741 * replacement text. @replacement is replaced literally, to
2742 * include backreferences use g_regex_replace().
2744 * Setting @start_position differs from just passing over a
2745 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2746 * case of a pattern that begins with any kind of lookbehind
2747 * assertion, such as "\b".
2749 * Returns: a newly allocated string containing the replacements
2754 g_regex_replace_literal (const GRegex *regex,
2755 const gchar *string,
2757 gint start_position,
2758 const gchar *replacement,
2759 GRegexMatchFlags match_options,
2762 g_return_val_if_fail (replacement != NULL, NULL);
2763 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2765 return g_regex_replace_eval (regex,
2766 string, string_len, start_position,
2768 literal_replacement,
2769 (gpointer)replacement,
2774 * g_regex_replace_eval:
2775 * @regex: a #GRegex structure from g_regex_new()
2776 * @string: (array length=string_len): string to perform matches against
2777 * @string_len: the length of @string, or -1 if @string is nul-terminated
2778 * @start_position: starting index of the string to match
2779 * @match_options: options for the match
2780 * @eval: a function to call for each match
2781 * @user_data: user data to pass to the function
2782 * @error: location to store the error occurring, or %NULL to ignore errors
2784 * Replaces occurrences of the pattern in regex with the output of
2785 * @eval for that occurrence.
2787 * Setting @start_position differs from just passing over a shortened
2788 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2789 * that begins with any kind of lookbehind assertion, such as "\b".
2791 * The following example uses g_regex_replace_eval() to replace multiple
2795 * eval_cb (const GMatchInfo *info,
2802 * match = g_match_info_fetch (info, 0);
2803 * r = g_hash_table_lookup ((GHashTable *)data, match);
2804 * g_string_append (res, r);
2816 * h = g_hash_table_new (g_str_hash, g_str_equal);
2818 * g_hash_table_insert (h, "1", "ONE");
2819 * g_hash_table_insert (h, "2", "TWO");
2820 * g_hash_table_insert (h, "3", "THREE");
2821 * g_hash_table_insert (h, "4", "FOUR");
2823 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2824 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2825 * g_hash_table_destroy (h);
2830 * Returns: a newly allocated string containing the replacements
2835 g_regex_replace_eval (const GRegex *regex,
2836 const gchar *string,
2838 gint start_position,
2839 GRegexMatchFlags match_options,
2840 GRegexEvalCallback eval,
2844 GMatchInfo *match_info;
2847 gboolean done = FALSE;
2848 GError *tmp_error = NULL;
2850 g_return_val_if_fail (regex != NULL, NULL);
2851 g_return_val_if_fail (string != NULL, NULL);
2852 g_return_val_if_fail (start_position >= 0, NULL);
2853 g_return_val_if_fail (eval != NULL, NULL);
2854 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2857 string_len = strlen (string);
2859 result = g_string_sized_new (string_len);
2861 /* run down the string making matches. */
2862 g_regex_match_full (regex, string, string_len, start_position,
2863 match_options, &match_info, &tmp_error);
2864 while (!done && g_match_info_matches (match_info))
2866 g_string_append_len (result,
2868 match_info->offsets[0] - str_pos);
2869 done = (*eval) (match_info, result, user_data);
2870 str_pos = match_info->offsets[1];
2871 g_match_info_next (match_info, &tmp_error);
2873 g_match_info_free (match_info);
2874 if (tmp_error != NULL)
2876 g_propagate_error (error, tmp_error);
2877 g_string_free (result, TRUE);
2881 g_string_append_len (result, string + str_pos, string_len - str_pos);
2882 return g_string_free (result, FALSE);
2886 * g_regex_check_replacement:
2887 * @replacement: the replacement string
2888 * @has_references: (out) (allow-none): location to store information about
2889 * references in @replacement or %NULL
2890 * @error: location to store error
2892 * Checks whether @replacement is a valid replacement string
2893 * (see g_regex_replace()), i.e. that all escape sequences in
2896 * If @has_references is not %NULL then @replacement is checked
2897 * for pattern references. For instance, replacement text 'foo\n'
2898 * does not contain references and may be evaluated without information
2899 * about actual match, but '\0\1' (whole match followed by first
2900 * subpattern) requires valid #GMatchInfo object.
2902 * Returns: whether @replacement is a valid replacement string
2907 g_regex_check_replacement (const gchar *replacement,
2908 gboolean *has_references,
2914 list = split_replacement (replacement, &tmp);
2918 g_propagate_error (error, tmp);
2923 *has_references = interpolation_list_needs_match (list);
2925 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2931 * g_regex_escape_nul:
2932 * @string: the string to escape
2933 * @length: the length of @string
2935 * Escapes the nul characters in @string to "\x00". It can be used
2936 * to compile a regex with embedded nul characters.
2938 * For completeness, @length can be -1 for a nul-terminated string.
2939 * In this case the output string will be of course equal to @string.
2941 * Returns: a newly-allocated escaped string
2946 g_regex_escape_nul (const gchar *string,
2950 const gchar *p, *piece_start, *end;
2953 g_return_val_if_fail (string != NULL, NULL);
2956 return g_strdup (string);
2958 end = string + length;
2959 p = piece_start = string;
2960 escaped = g_string_sized_new (length + 1);
2968 if (p != piece_start)
2970 /* copy the previous piece. */
2971 g_string_append_len (escaped, piece_start, p - piece_start);
2973 if ((backslashes & 1) == 0)
2974 g_string_append_c (escaped, '\\');
2975 g_string_append_c (escaped, 'x');
2976 g_string_append_c (escaped, '0');
2977 g_string_append_c (escaped, '0');
2987 p = g_utf8_next_char (p);
2992 if (piece_start < end)
2993 g_string_append_len (escaped, piece_start, end - piece_start);
2995 return g_string_free (escaped, FALSE);
2999 * g_regex_escape_string:
3000 * @string: (array length=length): the string to escape
3001 * @length: the length of @string, or -1 if @string is nul-terminated
3003 * Escapes the special characters used for regular expressions
3004 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
3005 * function is useful to dynamically generate regular expressions.
3007 * @string can contain nul characters that are replaced with "\0",
3008 * in this case remember to specify the correct length of @string
3011 * Returns: a newly-allocated escaped string
3016 g_regex_escape_string (const gchar *string,
3020 const char *p, *piece_start, *end;
3022 g_return_val_if_fail (string != NULL, NULL);
3025 length = strlen (string);
3027 end = string + length;
3028 p = piece_start = string;
3029 escaped = g_string_sized_new (length + 1);
3050 if (p != piece_start)
3051 /* copy the previous piece. */
3052 g_string_append_len (escaped, piece_start, p - piece_start);
3053 g_string_append_c (escaped, '\\');
3055 g_string_append_c (escaped, '0');
3057 g_string_append_c (escaped, *p);
3061 p = g_utf8_next_char (p);
3066 if (piece_start < end)
3067 g_string_append_len (escaped, piece_start, end - piece_start);
3069 return g_string_free (escaped, FALSE);