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)
117 /* Mask of all the possible values for GRegexMatchFlags. */
118 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
119 G_REGEX_MATCH_NOTBOL | \
120 G_REGEX_MATCH_NOTEOL | \
121 G_REGEX_MATCH_NOTEMPTY | \
122 G_REGEX_MATCH_PARTIAL | \
123 G_REGEX_MATCH_NEWLINE_CR | \
124 G_REGEX_MATCH_NEWLINE_LF | \
125 G_REGEX_MATCH_NEWLINE_CRLF | \
126 G_REGEX_MATCH_NEWLINE_ANY)
128 /* we rely on these flags having the same values */
129 G_STATIC_ASSERT (G_REGEX_CASELESS == PCRE_CASELESS);
130 G_STATIC_ASSERT (G_REGEX_MULTILINE == PCRE_MULTILINE);
131 G_STATIC_ASSERT (G_REGEX_DOTALL == PCRE_DOTALL);
132 G_STATIC_ASSERT (G_REGEX_EXTENDED == PCRE_EXTENDED);
133 G_STATIC_ASSERT (G_REGEX_ANCHORED == PCRE_ANCHORED);
134 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY == PCRE_DOLLAR_ENDONLY);
135 G_STATIC_ASSERT (G_REGEX_UNGREEDY == PCRE_UNGREEDY);
136 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE == PCRE_NO_AUTO_CAPTURE);
137 G_STATIC_ASSERT (G_REGEX_DUPNAMES == PCRE_DUPNAMES);
138 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR == PCRE_NEWLINE_CR);
139 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF == PCRE_NEWLINE_LF);
140 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
142 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED == PCRE_ANCHORED);
143 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL == PCRE_NOTBOL);
144 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL == PCRE_NOTEOL);
145 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY == PCRE_NOTEMPTY);
146 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL == PCRE_PARTIAL);
147 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR == PCRE_NEWLINE_CR);
148 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF == PCRE_NEWLINE_LF);
149 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
150 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY == PCRE_NEWLINE_ANY);
152 /* if the string is in UTF-8 use g_utf8_ functions, else use
154 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
155 g_utf8_next_char (s) : \
157 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
158 g_utf8_prev_char (s) : \
163 volatile gint ref_count; /* the ref count */
164 GRegex *regex; /* the regex */
165 GRegexMatchFlags match_opts; /* options used at match time on the regex */
166 gint matches; /* number of matching sub patterns */
167 gint pos; /* position in the string where last match left off */
168 gint n_offsets; /* number of offsets */
169 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
170 gint *workspace; /* workspace for pcre_dfa_exec() */
171 gint n_workspace; /* number of workspace elements */
172 const gchar *string; /* string passed to the match function */
173 gssize string_len; /* length of string */
178 volatile gint ref_count; /* the ref count for the immutable part */
179 gchar *pattern; /* the pattern */
180 pcre *pcre_re; /* compiled form of the pattern */
181 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
182 GRegexMatchFlags match_opts; /* options used at match time on the regex */
183 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
186 /* TRUE if ret is an error code, FALSE otherwise. */
187 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
189 typedef struct _InterpolationData InterpolationData;
190 static gboolean interpolation_list_needs_match (GList *list);
191 static gboolean interpolate_replacement (const GMatchInfo *match_info,
194 static GList *split_replacement (const gchar *replacement,
196 static void free_interpolation_data (InterpolationData *data);
200 match_error (gint errcode)
204 case PCRE_ERROR_NOMATCH:
207 case PCRE_ERROR_NULL:
208 /* NULL argument, this should not happen in GRegex */
209 g_warning ("A NULL argument was passed to PCRE");
211 case PCRE_ERROR_BADOPTION:
212 return "bad options";
213 case PCRE_ERROR_BADMAGIC:
214 return _("corrupted object");
215 case PCRE_ERROR_UNKNOWN_OPCODE:
216 return N_("internal error or corrupted object");
217 case PCRE_ERROR_NOMEMORY:
218 return _("out of memory");
219 case PCRE_ERROR_NOSUBSTRING:
220 /* not used by pcre_exec() */
222 case PCRE_ERROR_MATCHLIMIT:
223 return _("backtracking limit reached");
224 case PCRE_ERROR_CALLOUT:
225 /* callouts are not implemented */
227 case PCRE_ERROR_BADUTF8:
228 case PCRE_ERROR_BADUTF8_OFFSET:
229 /* we do not check if strings are valid */
231 case PCRE_ERROR_PARTIAL:
234 case PCRE_ERROR_BADPARTIAL:
235 return _("the pattern contains items not supported for partial matching");
236 case PCRE_ERROR_INTERNAL:
237 return _("internal error");
238 case PCRE_ERROR_BADCOUNT:
239 /* negative ovecsize, this should not happen in GRegex */
240 g_warning ("A negative ovecsize was passed to PCRE");
242 case PCRE_ERROR_DFA_UITEM:
243 return _("the pattern contains items not supported for partial matching");
244 case PCRE_ERROR_DFA_UCOND:
245 return _("back references as conditions are not supported for partial matching");
246 case PCRE_ERROR_DFA_UMLIMIT:
247 /* the match_field field is not used in GRegex */
249 case PCRE_ERROR_DFA_WSSIZE:
250 /* handled expanding the workspace */
252 case PCRE_ERROR_DFA_RECURSE:
253 case PCRE_ERROR_RECURSIONLIMIT:
254 return _("recursion limit reached");
255 case PCRE_ERROR_NULLWSLIMIT:
256 return _("workspace limit for empty substrings reached");
257 case PCRE_ERROR_BADNEWLINE:
258 return _("invalid combination of newline flags");
259 case PCRE_ERROR_BADOFFSET:
260 return _("bad offset");
261 case PCRE_ERROR_SHORTUTF8:
262 return _("short utf8");
263 case PCRE_ERROR_RECURSELOOP:
264 return _("recursion loop");
268 return _("unknown error");
272 translate_compile_error (gint *errcode, const gchar **errmsg)
274 /* Compile errors are created adding 100 to the error code returned
276 * If errcode is known we put the translatable error message in
277 * erromsg. If errcode is unknown we put the generic
278 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
279 * untranslated error message returned by PCRE.
280 * Note that there can be more PCRE errors with the same GRegexError
281 * and that some PCRE errors are useless for us.
287 case G_REGEX_ERROR_STRAY_BACKSLASH:
288 *errmsg = _("\\ at end of pattern");
290 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
291 *errmsg = _("\\c at end of pattern");
293 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
294 *errmsg = _("unrecognized character follows \\");
296 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
297 *errmsg = _("numbers out of order in {} quantifier");
299 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
300 *errmsg = _("number too big in {} quantifier");
302 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
303 *errmsg = _("missing terminating ] for character class");
305 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
306 *errmsg = _("invalid escape sequence in character class");
308 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
309 *errmsg = _("range out of order in character class");
311 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
312 *errmsg = _("nothing to repeat");
314 case 111: /* internal error: unexpected repeat */
315 *errcode = G_REGEX_ERROR_INTERNAL;
316 *errmsg = _("unexpected repeat");
318 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
319 *errmsg = _("unrecognized character after (? or (?-");
321 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
322 *errmsg = _("POSIX named classes are supported only within a class");
324 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
325 *errmsg = _("missing terminating )");
327 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
328 *errmsg = _("reference to non-existent subpattern");
330 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
331 *errmsg = _("missing ) after comment");
333 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
334 *errmsg = _("regular expression is too large");
336 case G_REGEX_ERROR_MEMORY_ERROR:
337 *errmsg = _("failed to get memory");
339 case 122: /* unmatched parentheses */
340 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
341 *errmsg = _(") without opening (");
343 case 123: /* internal error: code overflow */
344 *errcode = G_REGEX_ERROR_INTERNAL;
345 *errmsg = _("code overflow");
347 case 124: /* "unrecognized character after (?<\0 */
348 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
349 *errmsg = _("unrecognized character after (?<");
351 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
352 *errmsg = _("lookbehind assertion is not fixed length");
354 case G_REGEX_ERROR_MALFORMED_CONDITION:
355 *errmsg = _("malformed number or name after (?(");
357 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
358 *errmsg = _("conditional group contains more than two branches");
360 case G_REGEX_ERROR_ASSERTION_EXPECTED:
361 *errmsg = _("assertion expected after (?(");
364 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
365 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
366 * sequences here, '(?-54' would be an example for the second group.
368 *errmsg = _("(?R or (?[+-]digits must be followed by )");
370 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
371 *errmsg = _("unknown POSIX class name");
373 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
374 *errmsg = _("POSIX collating elements are not supported");
376 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
377 *errmsg = _("character value in \\x{...} sequence is too large");
379 case G_REGEX_ERROR_INVALID_CONDITION:
380 *errmsg = _("invalid condition (?(0)");
382 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
383 *errmsg = _("\\C not allowed in lookbehind assertion");
385 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
386 /* A number of Perl escapes are not handled by PCRE.
387 * Therefore it explicitly raises ERR37.
389 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
390 *errmsg = _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
392 case G_REGEX_ERROR_INFINITE_LOOP:
393 *errmsg = _("recursive call could loop indefinitely");
395 case 141: /* unrecognized character after (?P\0 */
396 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
397 *errmsg = _("unrecognized character after (?P");
399 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
400 *errmsg = _("missing terminator in subpattern name");
402 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
403 *errmsg = _("two named subpatterns have the same name");
405 case G_REGEX_ERROR_MALFORMED_PROPERTY:
406 *errmsg = _("malformed \\P or \\p sequence");
408 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
409 *errmsg = _("unknown property name after \\P or \\p");
411 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
412 *errmsg = _("subpattern name is too long (maximum 32 characters)");
414 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
415 *errmsg = _("too many named subpatterns (maximum 10,000)");
417 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
418 *errmsg = _("octal value is greater than \\377");
420 case 152: /* internal error: overran compiling workspace */
421 *errcode = G_REGEX_ERROR_INTERNAL;
422 *errmsg = _("overran compiling workspace");
424 case 153: /* internal error: previously-checked referenced subpattern not found */
425 *errcode = G_REGEX_ERROR_INTERNAL;
426 *errmsg = _("previously-checked referenced subpattern not found");
428 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
429 *errmsg = _("DEFINE group contains more than one branch");
431 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
432 *errmsg = _("inconsistent NEWLINE options");
434 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
435 *errmsg = _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
436 "number, or by a plain number");
438 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE:
439 *errmsg = _("a numbered reference must not be zero");
441 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
442 *errmsg = _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
444 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB:
445 *errmsg = _("(*VERB) not recognized");
447 case G_REGEX_ERROR_NUMBER_TOO_BIG:
448 *errmsg = _("number is too bug");
450 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME:
451 *errmsg = _("missing subpattern name after (?&");
453 case G_REGEX_ERROR_MISSING_DIGIT:
454 *errmsg = _("digit expected after (?+");
456 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME:
457 *errmsg = _("different names for subpatterns of the same number are not allowed");
459 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
460 *errmsg = _("(*MARK) must have an argument");
462 case G_REGEX_ERROR_INVALID_CONTROL_CHAR:
463 *errmsg = _( "\\c must be followed by an ASCII character");
465 case G_REGEX_ERROR_MISSING_NAME:
466 *errmsg = _("\\k is not followed by a braced, angle-bracketed, or quoted name");
468 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS:
469 *errmsg = _("\\N is not supported in a class");
471 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES:
472 *errmsg = _("too many forward references");
474 case G_REGEX_ERROR_NAME_TOO_LONG:
475 *errmsg = _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
478 case 116: /* erroffset passed as NULL */
479 /* This should not happen as we never pass a NULL erroffset */
480 g_warning ("erroffset passed as NULL");
481 *errcode = G_REGEX_ERROR_COMPILE;
483 case 117: /* unknown option bit(s) set */
484 /* This should not happen as we check options before passing them
485 * to pcre_compile2() */
486 g_warning ("unknown option bit(s) set");
487 *errcode = G_REGEX_ERROR_COMPILE;
489 case 132: /* this version of PCRE is compiled without UTF support */
490 case 144: /* invalid UTF-8 string */
491 case 145: /* support for \\P, \\p, and \\X has not been compiled */
492 case 167: /* this version of PCRE is not compiled with Unicode property support */
493 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
494 case 174: /* invalid UTF-16 string */
495 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
496 * and we do not check if strings are valid */
497 case 164: /* ] is an invalid data character in JavaScript compatibility mode */
498 /* This should not happen as we don't use PCRE_JAVASCRIPT_COMPAT */
499 g_warning ("%s", *errmsg);
500 *errcode = G_REGEX_ERROR_COMPILE;
502 case 170: /* internal error: unknown opcode in find_fixedlength() */
503 *errcode = G_REGEX_ERROR_INTERNAL;
507 *errcode = G_REGEX_ERROR_COMPILE;
514 match_info_new (const GRegex *regex,
521 GMatchInfo *match_info;
524 string_len = strlen (string);
526 match_info = g_new0 (GMatchInfo, 1);
527 match_info->ref_count = 1;
528 match_info->regex = g_regex_ref ((GRegex *)regex);
529 match_info->string = string;
530 match_info->string_len = string_len;
531 match_info->matches = PCRE_ERROR_NOMATCH;
532 match_info->pos = start_position;
533 match_info->match_opts = match_options;
537 /* These values should be enough for most cases, if they are not
538 * enough g_regex_match_all_full() will expand them. */
539 match_info->n_offsets = 24;
540 match_info->n_workspace = 100;
541 match_info->workspace = g_new (gint, match_info->n_workspace);
546 pcre_fullinfo (regex->pcre_re, regex->extra,
547 PCRE_INFO_CAPTURECOUNT, &capture_count);
548 match_info->n_offsets = (capture_count + 1) * 3;
551 match_info->offsets = g_new0 (gint, match_info->n_offsets);
552 /* Set an invalid position for the previous match. */
553 match_info->offsets[0] = -1;
554 match_info->offsets[1] = -1;
560 * g_match_info_get_regex:
561 * @match_info: a #GMatchInfo
563 * Returns #GRegex object used in @match_info. It belongs to Glib
564 * and must not be freed. Use g_regex_ref() if you need to keep it
565 * after you free @match_info object.
567 * Returns: #GRegex object used in @match_info
572 g_match_info_get_regex (const GMatchInfo *match_info)
574 g_return_val_if_fail (match_info != NULL, NULL);
575 return match_info->regex;
579 * g_match_info_get_string:
580 * @match_info: a #GMatchInfo
582 * Returns the string searched with @match_info. This is the
583 * string passed to g_regex_match() or g_regex_replace() so
584 * you may not free it before calling this function.
586 * Returns: the string searched with @match_info
591 g_match_info_get_string (const GMatchInfo *match_info)
593 g_return_val_if_fail (match_info != NULL, NULL);
594 return match_info->string;
599 * @match_info: a #GMatchInfo
601 * Increases reference count of @match_info by 1.
603 * Returns: @match_info
608 g_match_info_ref (GMatchInfo *match_info)
610 g_return_val_if_fail (match_info != NULL, NULL);
611 g_atomic_int_inc (&match_info->ref_count);
616 * g_match_info_unref:
617 * @match_info: a #GMatchInfo
619 * Decreases reference count of @match_info by 1. When reference count drops
620 * to zero, it frees all the memory associated with the match_info structure.
625 g_match_info_unref (GMatchInfo *match_info)
627 if (g_atomic_int_dec_and_test (&match_info->ref_count))
629 g_regex_unref (match_info->regex);
630 g_free (match_info->offsets);
631 g_free (match_info->workspace);
638 * @match_info: (allow-none): a #GMatchInfo, or %NULL
640 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
646 g_match_info_free (GMatchInfo *match_info)
648 if (match_info == NULL)
651 g_match_info_unref (match_info);
656 * @match_info: a #GMatchInfo structure
657 * @error: location to store the error occurring, or %NULL to ignore errors
659 * Scans for the next match using the same parameters of the previous
660 * call to g_regex_match_full() or g_regex_match() that returned
663 * The match is done on the string passed to the match function, so you
664 * cannot free it before calling this function.
666 * Returns: %TRUE is the string matched, %FALSE otherwise
671 g_match_info_next (GMatchInfo *match_info,
674 gint prev_match_start;
677 g_return_val_if_fail (match_info != NULL, FALSE);
678 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
679 g_return_val_if_fail (match_info->pos >= 0, FALSE);
681 prev_match_start = match_info->offsets[0];
682 prev_match_end = match_info->offsets[1];
684 if (match_info->pos > match_info->string_len)
686 /* we have reached the end of the string */
687 match_info->pos = -1;
688 match_info->matches = PCRE_ERROR_NOMATCH;
692 match_info->matches = pcre_exec (match_info->regex->pcre_re,
693 match_info->regex->extra,
695 match_info->string_len,
697 match_info->regex->match_opts | match_info->match_opts,
699 match_info->n_offsets);
700 if (IS_PCRE_ERROR (match_info->matches))
702 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
703 _("Error while matching regular expression %s: %s"),
704 match_info->regex->pattern, match_error (match_info->matches));
708 /* avoid infinite loops if the pattern is an empty string or something
710 if (match_info->pos == match_info->offsets[1])
712 if (match_info->pos > match_info->string_len)
714 /* we have reached the end of the string */
715 match_info->pos = -1;
716 match_info->matches = PCRE_ERROR_NOMATCH;
720 match_info->pos = NEXT_CHAR (match_info->regex,
721 &match_info->string[match_info->pos]) -
726 match_info->pos = match_info->offsets[1];
729 /* it's possible to get two identical matches when we are matching
730 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
731 * the string is "RegExTest" we have:
732 * - search at position 0: match from 0 to 0
733 * - search at position 1: match from 3 to 3
734 * - search at position 3: match from 3 to 3 (duplicate)
735 * - search at position 4: match from 5 to 5
736 * - search at position 5: match from 5 to 5 (duplicate)
737 * - search at position 6: no match -> stop
738 * so we have to ignore the duplicates.
739 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
740 if (match_info->matches >= 0 &&
741 prev_match_start == match_info->offsets[0] &&
742 prev_match_end == match_info->offsets[1])
744 /* ignore this match and search the next one */
745 return g_match_info_next (match_info, error);
748 return match_info->matches >= 0;
752 * g_match_info_matches:
753 * @match_info: a #GMatchInfo structure
755 * Returns whether the previous match operation succeeded.
757 * Returns: %TRUE if the previous match operation succeeded,
763 g_match_info_matches (const GMatchInfo *match_info)
765 g_return_val_if_fail (match_info != NULL, FALSE);
767 return match_info->matches >= 0;
771 * g_match_info_get_match_count:
772 * @match_info: a #GMatchInfo structure
774 * Retrieves the number of matched substrings (including substring 0,
775 * that is the whole matched text), so 1 is returned if the pattern
776 * has no substrings in it and 0 is returned if the match failed.
778 * If the last match was obtained using the DFA algorithm, that is
779 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
780 * count is not that of the number of capturing parentheses but that of
781 * the number of matched substrings.
783 * Returns: Number of matched substrings, or -1 if an error occurred
788 g_match_info_get_match_count (const GMatchInfo *match_info)
790 g_return_val_if_fail (match_info, -1);
792 if (match_info->matches == PCRE_ERROR_NOMATCH)
795 else if (match_info->matches < PCRE_ERROR_NOMATCH)
800 return match_info->matches;
804 * g_match_info_is_partial_match:
805 * @match_info: a #GMatchInfo structure
807 * Usually if the string passed to g_regex_match*() matches as far as
808 * it goes, but is too short to match the entire pattern, %FALSE is
809 * returned. There are circumstances where it might be helpful to
810 * distinguish this case from other cases in which there is no match.
812 * Consider, for example, an application where a human is required to
813 * type in data for a field with specific formatting requirements. An
814 * example might be a date in the form ddmmmyy, defined by the pattern
815 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
816 * If the application sees the user’s keystrokes one by one, and can
817 * check that what has been typed so far is potentially valid, it is
818 * able to raise an error as soon as a mistake is made.
820 * GRegex supports the concept of partial matching by means of the
821 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
822 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
823 * for a complete match, %FALSE otherwise. But, when these functions
824 * return %FALSE, you can check if the match was partial calling
825 * g_match_info_is_partial_match().
827 * When using partial matching you cannot use g_match_info_fetch*().
829 * Because of the way certain internal optimizations are implemented
830 * the partial matching algorithm cannot be used with all patterns.
831 * So repeated single characters such as "a{2,4}" and repeated single
832 * meta-sequences such as "\d+" are not permitted if the maximum number
833 * of occurrences is greater than one. Optional items such as "\d?"
834 * (where the maximum is one) are permitted. Quantifiers with any values
835 * are permitted after parentheses, so the invalid examples above can be
836 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
837 * for a pattern that does not conform to the restrictions, matching
838 * functions return an error.
840 * Returns: %TRUE if the match was partial, %FALSE otherwise
845 g_match_info_is_partial_match (const GMatchInfo *match_info)
847 g_return_val_if_fail (match_info != NULL, FALSE);
849 return match_info->matches == PCRE_ERROR_PARTIAL;
853 * g_match_info_expand_references:
854 * @match_info: (allow-none): a #GMatchInfo or %NULL
855 * @string_to_expand: the string to expand
856 * @error: location to store the error occurring, or %NULL to ignore errors
858 * Returns a new string containing the text in @string_to_expand with
859 * references and escape sequences expanded. References refer to the last
860 * match done with @string against @regex and have the same syntax used by
863 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
864 * passed to g_regex_new().
866 * The backreferences are extracted from the string passed to the match
867 * function, so you cannot call this function after freeing the string.
869 * @match_info may be %NULL in which case @string_to_expand must not
870 * contain references. For instance "foo\n" does not refer to an actual
871 * pattern and '\n' merely will be replaced with \n character,
872 * while to expand "\0" (whole match) one needs the result of a match.
873 * Use g_regex_check_replacement() to find out whether @string_to_expand
874 * contains references.
876 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
881 g_match_info_expand_references (const GMatchInfo *match_info,
882 const gchar *string_to_expand,
887 GError *tmp_error = NULL;
889 g_return_val_if_fail (string_to_expand != NULL, NULL);
890 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
892 list = split_replacement (string_to_expand, &tmp_error);
893 if (tmp_error != NULL)
895 g_propagate_error (error, tmp_error);
899 if (!match_info && interpolation_list_needs_match (list))
901 g_critical ("String '%s' contains references to the match, can't "
902 "expand references without GMatchInfo object",
907 result = g_string_sized_new (strlen (string_to_expand));
908 interpolate_replacement (match_info, result, list);
910 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
912 return g_string_free (result, FALSE);
916 * g_match_info_fetch:
917 * @match_info: #GMatchInfo structure
918 * @match_num: number of the sub expression
920 * Retrieves the text matching the @match_num<!-- -->'th capturing
921 * parentheses. 0 is the full text of the match, 1 is the first paren
922 * set, 2 the second, and so on.
924 * If @match_num is a valid sub pattern but it didn't match anything
925 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
926 * string is returned.
928 * If the match was obtained using the DFA algorithm, that is using
929 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
930 * string is not that of a set of parentheses but that of a matched
931 * substring. Substrings are matched in reverse order of length, so
932 * 0 is the longest match.
934 * The string is fetched from the string passed to the match function,
935 * so you cannot call this function after freeing the string.
937 * Returns: (allow-none): The matched substring, or %NULL if an error
938 * occurred. You have to free the string yourself
943 g_match_info_fetch (const GMatchInfo *match_info,
946 /* we cannot use pcre_get_substring() because it allocates the
947 * string using pcre_malloc(). */
951 g_return_val_if_fail (match_info != NULL, NULL);
952 g_return_val_if_fail (match_num >= 0, NULL);
954 /* match_num does not exist or it didn't matched, i.e. matching "b"
955 * against "(a)?b" then group 0 is empty. */
956 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
958 else if (start == -1)
959 match = g_strdup ("");
961 match = g_strndup (&match_info->string[start], end - start);
967 * g_match_info_fetch_pos:
968 * @match_info: #GMatchInfo structure
969 * @match_num: number of the sub expression
970 * @start_pos: (out) (allow-none): pointer to location where to store
971 * the start position, or %NULL
972 * @end_pos: (out) (allow-none): pointer to location where to store
973 * the end position, or %NULL
975 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
976 * parentheses. 0 is the full text of the match, 1 is the first
977 * paren set, 2 the second, and so on.
979 * If @match_num is a valid sub pattern but it didn't match anything
980 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
981 * and @end_pos are set to -1 and %TRUE is returned.
983 * If the match was obtained using the DFA algorithm, that is using
984 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
985 * position is not that of a set of parentheses but that of a matched
986 * substring. Substrings are matched in reverse order of length, so
987 * 0 is the longest match.
989 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
990 * the position cannot be fetched, @start_pos and @end_pos are left
996 g_match_info_fetch_pos (const GMatchInfo *match_info,
1001 g_return_val_if_fail (match_info != NULL, FALSE);
1002 g_return_val_if_fail (match_num >= 0, FALSE);
1004 /* make sure the sub expression number they're requesting is less than
1005 * the total number of sub expressions that were matched. */
1006 if (match_num >= match_info->matches)
1009 if (start_pos != NULL)
1010 *start_pos = match_info->offsets[2 * match_num];
1012 if (end_pos != NULL)
1013 *end_pos = match_info->offsets[2 * match_num + 1];
1019 * Returns number of first matched subpattern with name @name.
1020 * There may be more than one in case when DUPNAMES is used,
1021 * and not all subpatterns with that name match;
1022 * pcre_get_stringnumber() does not work in that case.
1025 get_matched_substring_number (const GMatchInfo *match_info,
1029 gchar *first, *last;
1032 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
1033 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
1035 /* This code is copied from pcre_get.c: get_first_set() */
1036 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
1044 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
1046 gint n = (entry[0] << 8) + entry[1];
1047 if (match_info->offsets[n*2] >= 0)
1051 return (first[0] << 8) + first[1];
1055 * g_match_info_fetch_named:
1056 * @match_info: #GMatchInfo structure
1057 * @name: name of the subexpression
1059 * Retrieves the text matching the capturing parentheses named @name.
1061 * If @name is a valid sub pattern name but it didn't match anything
1062 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1063 * then an empty string is returned.
1065 * The string is fetched from the string passed to the match function,
1066 * so you cannot call this function after freeing the string.
1068 * Returns: (allow-none): The matched substring, or %NULL if an error
1069 * occurred. You have to free the string yourself
1074 g_match_info_fetch_named (const GMatchInfo *match_info,
1077 /* we cannot use pcre_get_named_substring() because it allocates the
1078 * string using pcre_malloc(). */
1081 g_return_val_if_fail (match_info != NULL, NULL);
1082 g_return_val_if_fail (name != NULL, NULL);
1084 num = get_matched_substring_number (match_info, name);
1088 return g_match_info_fetch (match_info, num);
1092 * g_match_info_fetch_named_pos:
1093 * @match_info: #GMatchInfo structure
1094 * @name: name of the subexpression
1095 * @start_pos: (out) (allow-none): pointer to location where to store
1096 * the start position, or %NULL
1097 * @end_pos: (out) (allow-none): pointer to location where to store
1098 * the end position, or %NULL
1100 * Retrieves the position in bytes of the capturing parentheses named @name.
1102 * If @name is a valid sub pattern name but it didn't match anything
1103 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1104 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1106 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1107 * If the position cannot be fetched, @start_pos and @end_pos
1108 * are left unchanged.
1113 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
1120 g_return_val_if_fail (match_info != NULL, FALSE);
1121 g_return_val_if_fail (name != NULL, FALSE);
1123 num = get_matched_substring_number (match_info, name);
1127 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
1131 * g_match_info_fetch_all:
1132 * @match_info: a #GMatchInfo structure
1134 * Bundles up pointers to each of the matching substrings from a match
1135 * and stores them in an array of gchar pointers. The first element in
1136 * the returned array is the match number 0, i.e. the entire matched
1139 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1140 * "b" against "(a)?b") then an empty string is inserted.
1142 * If the last match was obtained using the DFA algorithm, that is using
1143 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1144 * strings are not that matched by sets of parentheses but that of the
1145 * matched substring. Substrings are matched in reverse order of length,
1146 * so the first one is the longest match.
1148 * The strings are fetched from the string passed to the match function,
1149 * so you cannot call this function after freeing the string.
1151 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
1152 * It must be freed using g_strfreev(). If the previous match failed
1158 g_match_info_fetch_all (const GMatchInfo *match_info)
1160 /* we cannot use pcre_get_substring_list() because the returned value
1161 * isn't suitable for g_strfreev(). */
1165 g_return_val_if_fail (match_info != NULL, NULL);
1167 if (match_info->matches < 0)
1170 result = g_new (gchar *, match_info->matches + 1);
1171 for (i = 0; i < match_info->matches; i++)
1172 result[i] = g_match_info_fetch (match_info, i);
1182 g_regex_error_quark (void)
1184 static GQuark error_quark = 0;
1186 if (error_quark == 0)
1187 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1196 * Increases reference count of @regex by 1.
1203 g_regex_ref (GRegex *regex)
1205 g_return_val_if_fail (regex != NULL, NULL);
1206 g_atomic_int_inc (®ex->ref_count);
1214 * Decreases reference count of @regex by 1. When reference count drops
1215 * to zero, it frees all the memory associated with the regex structure.
1220 g_regex_unref (GRegex *regex)
1222 g_return_if_fail (regex != NULL);
1224 if (g_atomic_int_dec_and_test (®ex->ref_count))
1226 g_free (regex->pattern);
1227 if (regex->pcre_re != NULL)
1228 pcre_free (regex->pcre_re);
1229 if (regex->extra != NULL)
1230 pcre_free (regex->extra);
1237 * @pattern: the regular expression
1238 * @compile_options: compile options for the regular expression, or 0
1239 * @match_options: match options for the regular expression, or 0
1240 * @error: return location for a #GError
1242 * Compiles the regular expression to an internal form, and does
1243 * the initial setup of the #GRegex structure.
1245 * Returns: a #GRegex structure. Call g_regex_unref() when you
1251 g_regex_new (const gchar *pattern,
1252 GRegexCompileFlags compile_options,
1253 GRegexMatchFlags match_options,
1258 const gchar *errmsg;
1261 gboolean optimize = FALSE;
1262 static gsize initialised;
1263 unsigned long int pcre_compile_options;
1265 g_return_val_if_fail (pattern != NULL, NULL);
1266 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1267 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1268 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1270 if (g_once_init_enter (&initialised))
1275 pcre_config (PCRE_CONFIG_UTF8, &support);
1278 msg = N_("PCRE library is compiled without UTF8 support");
1279 g_critical ("%s", msg);
1280 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1284 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
1287 msg = N_("PCRE library is compiled without UTF8 properties support");
1288 g_critical ("%s", msg);
1289 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1293 g_once_init_leave (&initialised, TRUE);
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 /* compile the pattern */
1326 re = pcre_compile2 (pattern, compile_options, &errcode,
1327 &errmsg, &erroffset, NULL);
1329 /* if the compilation failed, set the error member and return
1335 /* Translate the PCRE error code to GRegexError and use a translated
1336 * error message if possible */
1337 translate_compile_error (&errcode, &errmsg);
1339 /* PCRE uses byte offsets but we want to show character offsets */
1340 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1342 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1343 _("Error while compiling regular "
1344 "expression %s at char %d: %s"),
1345 pattern, erroffset, errmsg);
1346 g_propagate_error (error, tmp_error);
1351 /* For options set at the beginning of the pattern, pcre puts them into
1352 * compile options, e.g. "(?i)foo" will make the pcre structure store
1353 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1354 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1355 compile_options = pcre_compile_options;
1357 if (!(compile_options & G_REGEX_DUPNAMES))
1359 gboolean jchanged = FALSE;
1360 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1362 compile_options |= G_REGEX_DUPNAMES;
1365 regex = g_new0 (GRegex, 1);
1366 regex->ref_count = 1;
1367 regex->pattern = g_strdup (pattern);
1368 regex->pcre_re = re;
1369 regex->compile_opts = compile_options;
1370 regex->match_opts = match_options;
1374 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1377 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1378 G_REGEX_ERROR_OPTIMIZE,
1379 _("Error while optimizing "
1380 "regular expression %s: %s"),
1383 g_propagate_error (error, tmp_error);
1385 g_regex_unref (regex);
1394 * g_regex_get_pattern:
1395 * @regex: a #GRegex structure
1397 * Gets the pattern string associated with @regex, i.e. a copy of
1398 * the string passed to g_regex_new().
1400 * Returns: the pattern of @regex
1405 g_regex_get_pattern (const GRegex *regex)
1407 g_return_val_if_fail (regex != NULL, NULL);
1409 return regex->pattern;
1413 * g_regex_get_max_backref:
1416 * Returns the number of the highest back reference
1417 * in the pattern, or 0 if the pattern does not contain
1420 * Returns: the number of the highest back reference
1425 g_regex_get_max_backref (const GRegex *regex)
1429 pcre_fullinfo (regex->pcre_re, regex->extra,
1430 PCRE_INFO_BACKREFMAX, &value);
1436 * g_regex_get_capture_count:
1439 * Returns the number of capturing subpatterns in the pattern.
1441 * Returns: the number of capturing subpatterns
1446 g_regex_get_capture_count (const GRegex *regex)
1450 pcre_fullinfo (regex->pcre_re, regex->extra,
1451 PCRE_INFO_CAPTURECOUNT, &value);
1457 * g_regex_get_compile_flags:
1460 * Returns the compile options that @regex was created with.
1462 * Returns: flags from #GRegexCompileFlags
1467 g_regex_get_compile_flags (const GRegex *regex)
1469 g_return_val_if_fail (regex != NULL, 0);
1471 return regex->compile_opts;
1475 * g_regex_get_match_flags:
1478 * Returns the match options that @regex was created with.
1480 * Returns: flags from #GRegexMatchFlags
1485 g_regex_get_match_flags (const GRegex *regex)
1487 g_return_val_if_fail (regex != NULL, 0);
1489 return regex->match_opts;
1493 * g_regex_match_simple:
1494 * @pattern: the regular expression
1495 * @string: the string to scan for matches
1496 * @compile_options: compile options for the regular expression, or 0
1497 * @match_options: match options, or 0
1499 * Scans for a match in @string for @pattern.
1501 * This function is equivalent to g_regex_match() but it does not
1502 * require to compile the pattern with g_regex_new(), avoiding some
1503 * lines of code when you need just to do a match without extracting
1504 * substrings, capture counts, and so on.
1506 * If this function is to be called on the same @pattern more than
1507 * once, it's more efficient to compile the pattern once with
1508 * g_regex_new() and then use g_regex_match().
1510 * Returns: %TRUE if the string matched, %FALSE otherwise
1515 g_regex_match_simple (const gchar *pattern,
1516 const gchar *string,
1517 GRegexCompileFlags compile_options,
1518 GRegexMatchFlags match_options)
1523 regex = g_regex_new (pattern, compile_options, 0, NULL);
1526 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1527 g_regex_unref (regex);
1533 * @regex: a #GRegex structure from g_regex_new()
1534 * @string: the string to scan for matches
1535 * @match_options: match options
1536 * @match_info: (out) (allow-none): pointer to location where to store
1537 * the #GMatchInfo, or %NULL if you do not need it
1539 * Scans for a match in string for the pattern in @regex.
1540 * The @match_options are combined with the match options specified
1541 * when the @regex structure was created, letting you have more
1542 * flexibility in reusing #GRegex structures.
1544 * A #GMatchInfo structure, used to get information on the match,
1545 * is stored in @match_info if not %NULL. Note that if @match_info
1546 * is not %NULL then it is created even if the function returns %FALSE,
1547 * i.e. you must free it regardless if regular expression actually matched.
1549 * To retrieve all the non-overlapping matches of the pattern in
1550 * string you can use g_match_info_next().
1554 * print_uppercase_words (const gchar *string)
1556 * /* Print all uppercase-only words. */
1558 * GMatchInfo *match_info;
1560 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1561 * g_regex_match (regex, string, 0, &match_info);
1562 * while (g_match_info_matches (match_info))
1564 * gchar *word = g_match_info_fetch (match_info, 0);
1565 * g_print ("Found: %s\n", word);
1567 * g_match_info_next (match_info, NULL);
1569 * g_match_info_free (match_info);
1570 * g_regex_unref (regex);
1574 * @string is not copied and is used in #GMatchInfo internally. If
1575 * you use any #GMatchInfo method (except g_match_info_free()) after
1576 * freeing or modifying @string then the behaviour is undefined.
1578 * Returns: %TRUE is the string matched, %FALSE otherwise
1583 g_regex_match (const GRegex *regex,
1584 const gchar *string,
1585 GRegexMatchFlags match_options,
1586 GMatchInfo **match_info)
1588 return g_regex_match_full (regex, string, -1, 0, match_options,
1593 * g_regex_match_full:
1594 * @regex: a #GRegex structure from g_regex_new()
1595 * @string: (array length=string_len): the string to scan for matches
1596 * @string_len: the length of @string, or -1 if @string is nul-terminated
1597 * @start_position: starting index of the string to match
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
1601 * @error: location to store the error occurring, or %NULL to ignore errors
1603 * Scans for a match in string for the pattern in @regex.
1604 * The @match_options are combined with the match options specified
1605 * when the @regex structure was created, letting you have more
1606 * flexibility in reusing #GRegex structures.
1608 * Setting @start_position differs from just passing over a shortened
1609 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1610 * that begins with any kind of lookbehind assertion, such as "\b".
1612 * A #GMatchInfo structure, used to get information on the match, is
1613 * stored in @match_info if not %NULL. Note that if @match_info is
1614 * not %NULL then it is created even if the function returns %FALSE,
1615 * i.e. you must free it regardless if regular expression actually
1618 * @string is not copied and is used in #GMatchInfo internally. If
1619 * you use any #GMatchInfo method (except g_match_info_free()) after
1620 * freeing or modifying @string then the behaviour is undefined.
1622 * To retrieve all the non-overlapping matches of the pattern in
1623 * string you can use g_match_info_next().
1627 * print_uppercase_words (const gchar *string)
1629 * /* Print all uppercase-only words. */
1631 * GMatchInfo *match_info;
1632 * GError *error = NULL;
1634 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1635 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1636 * while (g_match_info_matches (match_info))
1638 * gchar *word = g_match_info_fetch (match_info, 0);
1639 * g_print ("Found: %s\n", word);
1641 * g_match_info_next (match_info, &error);
1643 * g_match_info_free (match_info);
1644 * g_regex_unref (regex);
1645 * if (error != NULL)
1647 * g_printerr ("Error while matching: %s\n", error->message);
1648 * g_error_free (error);
1653 * Returns: %TRUE is the string matched, %FALSE otherwise
1658 g_regex_match_full (const GRegex *regex,
1659 const gchar *string,
1661 gint start_position,
1662 GRegexMatchFlags match_options,
1663 GMatchInfo **match_info,
1669 g_return_val_if_fail (regex != NULL, FALSE);
1670 g_return_val_if_fail (string != NULL, FALSE);
1671 g_return_val_if_fail (start_position >= 0, FALSE);
1672 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1673 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1675 info = match_info_new (regex, string, string_len, start_position,
1676 match_options, FALSE);
1677 match_ok = g_match_info_next (info, error);
1678 if (match_info != NULL)
1681 g_match_info_free (info);
1687 * g_regex_match_all:
1688 * @regex: a #GRegex structure from g_regex_new()
1689 * @string: the string to scan for matches
1690 * @match_options: match options
1691 * @match_info: (out) (allow-none): pointer to location where to store
1692 * the #GMatchInfo, or %NULL if you do not need it
1694 * Using the standard algorithm for regular expression matching only
1695 * the longest match in the string is retrieved. This function uses
1696 * a different algorithm so it can retrieve all the possible matches.
1697 * For more documentation see g_regex_match_all_full().
1699 * A #GMatchInfo structure, used to get information on the match, is
1700 * stored in @match_info if not %NULL. Note that if @match_info is
1701 * not %NULL then it is created even if the function returns %FALSE,
1702 * i.e. you must free it regardless if regular expression actually
1705 * @string is not copied and is used in #GMatchInfo internally. If
1706 * you use any #GMatchInfo method (except g_match_info_free()) after
1707 * freeing or modifying @string then the behaviour is undefined.
1709 * Returns: %TRUE is the string matched, %FALSE otherwise
1714 g_regex_match_all (const GRegex *regex,
1715 const gchar *string,
1716 GRegexMatchFlags match_options,
1717 GMatchInfo **match_info)
1719 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1724 * g_regex_match_all_full:
1725 * @regex: a #GRegex structure from g_regex_new()
1726 * @string: (array length=string_len): the string to scan for matches
1727 * @string_len: the length of @string, or -1 if @string is nul-terminated
1728 * @start_position: starting index of the string to match
1729 * @match_options: match options
1730 * @match_info: (out) (allow-none): pointer to location where to store
1731 * the #GMatchInfo, or %NULL if you do not need it
1732 * @error: location to store the error occurring, or %NULL to ignore errors
1734 * Using the standard algorithm for regular expression matching only
1735 * the longest match in the string is retrieved, it is not possible
1736 * to obtain all the available matches. For instance matching
1737 * "<a> <b> <c>" against the pattern "<.*>"
1738 * you get "<a> <b> <c>".
1740 * This function uses a different algorithm (called DFA, i.e. deterministic
1741 * finite automaton), so it can retrieve all the possible matches, all
1742 * starting at the same point in the string. For instance matching
1743 * "<a> <b> <c>" against the pattern "<.*>"
1744 * you would obtain three matches: "<a> <b> <c>",
1745 * "<a> <b>" and "<a>".
1747 * The number of matched strings is retrieved using
1748 * g_match_info_get_match_count(). To obtain the matched strings and
1749 * their position you can use, respectively, g_match_info_fetch() and
1750 * g_match_info_fetch_pos(). Note that the strings are returned in
1751 * reverse order of length; that is, the longest matching string is
1754 * Note that the DFA algorithm is slower than the standard one and it
1755 * is not able to capture substrings, so backreferences do not work.
1757 * Setting @start_position differs from just passing over a shortened
1758 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1759 * that begins with any kind of lookbehind assertion, such as "\b".
1761 * A #GMatchInfo structure, used to get information on the match, is
1762 * stored in @match_info if not %NULL. Note that if @match_info is
1763 * not %NULL then it is created even if the function returns %FALSE,
1764 * i.e. you must free it regardless if regular expression actually
1767 * @string is not copied and is used in #GMatchInfo internally. If
1768 * you use any #GMatchInfo method (except g_match_info_free()) after
1769 * freeing or modifying @string then the behaviour is undefined.
1771 * Returns: %TRUE is the string matched, %FALSE otherwise
1776 g_regex_match_all_full (const GRegex *regex,
1777 const gchar *string,
1779 gint start_position,
1780 GRegexMatchFlags match_options,
1781 GMatchInfo **match_info,
1787 g_return_val_if_fail (regex != NULL, FALSE);
1788 g_return_val_if_fail (string != NULL, FALSE);
1789 g_return_val_if_fail (start_position >= 0, FALSE);
1790 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1791 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1793 info = match_info_new (regex, string, string_len, start_position,
1794 match_options, TRUE);
1800 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1801 info->string, info->string_len,
1803 regex->match_opts | match_options,
1804 info->offsets, info->n_offsets,
1805 info->workspace, info->n_workspace);
1806 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1808 /* info->workspace is too small. */
1809 info->n_workspace *= 2;
1810 info->workspace = g_realloc (info->workspace,
1811 info->n_workspace * sizeof (gint));
1814 else if (info->matches == 0)
1816 /* info->offsets is too small. */
1817 info->n_offsets *= 2;
1818 info->offsets = g_realloc (info->offsets,
1819 info->n_offsets * sizeof (gint));
1822 else if (IS_PCRE_ERROR (info->matches))
1824 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1825 _("Error while matching regular expression %s: %s"),
1826 regex->pattern, match_error (info->matches));
1830 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1833 if (match_info != NULL)
1836 g_match_info_free (info);
1838 return info->matches >= 0;
1842 * g_regex_get_string_number:
1843 * @regex: #GRegex structure
1844 * @name: name of the subexpression
1846 * Retrieves the number of the subexpression named @name.
1848 * Returns: The number of the subexpression or -1 if @name
1854 g_regex_get_string_number (const GRegex *regex,
1859 g_return_val_if_fail (regex != NULL, -1);
1860 g_return_val_if_fail (name != NULL, -1);
1862 num = pcre_get_stringnumber (regex->pcre_re, name);
1863 if (num == PCRE_ERROR_NOSUBSTRING)
1870 * g_regex_split_simple:
1871 * @pattern: the regular expression
1872 * @string: the string to scan for matches
1873 * @compile_options: compile options for the regular expression, or 0
1874 * @match_options: match options, or 0
1876 * Breaks the string on the pattern, and returns an array of
1877 * the tokens. If the pattern contains capturing parentheses,
1878 * then the text for each of the substrings will also be returned.
1879 * If the pattern does not match anywhere in the string, then the
1880 * whole string is returned as the first token.
1882 * This function is equivalent to g_regex_split() but it does
1883 * not require to compile the pattern with g_regex_new(), avoiding
1884 * some lines of code when you need just to do a split without
1885 * extracting substrings, capture counts, and so on.
1887 * If this function is to be called on the same @pattern more than
1888 * once, it's more efficient to compile the pattern once with
1889 * g_regex_new() and then use g_regex_split().
1891 * As a special case, the result of splitting the empty string ""
1892 * is an empty vector, not a vector containing a single string.
1893 * The reason for this special case is that being able to represent
1894 * a empty vector is typically more useful than consistent handling
1895 * of empty elements. If you do need to represent empty elements,
1896 * you'll need to check for the empty string before calling this
1899 * A pattern that can match empty strings splits @string into
1900 * separate characters wherever it matches the empty string between
1901 * characters. For example splitting "ab c" using as a separator
1902 * "\s*", you will get "a", "b" and "c".
1904 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1909 g_regex_split_simple (const gchar *pattern,
1910 const gchar *string,
1911 GRegexCompileFlags compile_options,
1912 GRegexMatchFlags match_options)
1917 regex = g_regex_new (pattern, compile_options, 0, NULL);
1921 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1922 g_regex_unref (regex);
1928 * @regex: a #GRegex structure
1929 * @string: the string to split with the pattern
1930 * @match_options: match time option flags
1932 * Breaks the string on the pattern, and returns an array of the tokens.
1933 * If the pattern contains capturing parentheses, then the text for each
1934 * of the substrings will also be returned. If the pattern does not match
1935 * anywhere in the string, then the whole string is returned as the first
1938 * As a special case, the result of splitting the empty string "" is an
1939 * empty vector, not a vector containing a single string. The reason for
1940 * this special case is that being able to represent a empty vector is
1941 * typically more useful than consistent handling of empty elements. If
1942 * you do need to represent empty elements, you'll need to check for the
1943 * empty string before calling this function.
1945 * A pattern that can match empty strings splits @string into separate
1946 * characters wherever it matches the empty string between characters.
1947 * For example splitting "ab c" using as a separator "\s*", you will get
1950 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1955 g_regex_split (const GRegex *regex,
1956 const gchar *string,
1957 GRegexMatchFlags match_options)
1959 return g_regex_split_full (regex, string, -1, 0,
1960 match_options, 0, NULL);
1964 * g_regex_split_full:
1965 * @regex: a #GRegex structure
1966 * @string: (array length=string_len): the string to split with the pattern
1967 * @string_len: the length of @string, or -1 if @string is nul-terminated
1968 * @start_position: starting index of the string to match
1969 * @match_options: match time option flags
1970 * @max_tokens: the maximum number of tokens to split @string into.
1971 * If this is less than 1, the string is split completely
1972 * @error: return location for a #GError
1974 * Breaks the string on the pattern, and returns an array of the tokens.
1975 * If the pattern contains capturing parentheses, then the text for each
1976 * of the substrings will also be returned. If the pattern does not match
1977 * anywhere in the string, then the whole string is returned as the first
1980 * As a special case, the result of splitting the empty string "" is an
1981 * empty vector, not a vector containing a single string. The reason for
1982 * this special case is that being able to represent a empty vector is
1983 * typically more useful than consistent handling of empty elements. If
1984 * you do need to represent empty elements, you'll need to check for the
1985 * empty string before calling this function.
1987 * A pattern that can match empty strings splits @string into separate
1988 * characters wherever it matches the empty string between characters.
1989 * For example splitting "ab c" using as a separator "\s*", you will get
1992 * Setting @start_position differs from just passing over a shortened
1993 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1994 * that begins with any kind of lookbehind assertion, such as "\b".
1996 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2001 g_regex_split_full (const GRegex *regex,
2002 const gchar *string,
2004 gint start_position,
2005 GRegexMatchFlags match_options,
2009 GError *tmp_error = NULL;
2010 GMatchInfo *match_info;
2015 /* position of the last separator. */
2016 gint last_separator_end;
2017 /* was the last match 0 bytes long? */
2018 gboolean last_match_is_empty;
2019 /* the returned array of char **s */
2020 gchar **string_list;
2022 g_return_val_if_fail (regex != NULL, NULL);
2023 g_return_val_if_fail (string != NULL, NULL);
2024 g_return_val_if_fail (start_position >= 0, NULL);
2025 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2026 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2028 if (max_tokens <= 0)
2029 max_tokens = G_MAXINT;
2032 string_len = strlen (string);
2034 /* zero-length string */
2035 if (string_len - start_position == 0)
2036 return g_new0 (gchar *, 1);
2038 if (max_tokens == 1)
2040 string_list = g_new0 (gchar *, 2);
2041 string_list[0] = g_strndup (&string[start_position],
2042 string_len - start_position);
2048 last_separator_end = start_position;
2049 last_match_is_empty = FALSE;
2051 match_ok = g_regex_match_full (regex, string, string_len, start_position,
2052 match_options, &match_info, &tmp_error);
2054 while (tmp_error == NULL)
2058 last_match_is_empty =
2059 (match_info->offsets[0] == match_info->offsets[1]);
2061 /* we need to skip empty separators at the same position of the end
2062 * of another separator. e.g. the string is "a b" and the separator
2063 * is " *", so from 1 to 2 we have a match and at position 2 we have
2064 * an empty match. */
2065 if (last_separator_end != match_info->offsets[1])
2070 token = g_strndup (string + last_separator_end,
2071 match_info->offsets[0] - last_separator_end);
2072 list = g_list_prepend (list, token);
2075 /* if there were substrings, these need to be added to
2077 match_count = g_match_info_get_match_count (match_info);
2078 if (match_count > 1)
2080 for (i = 1; i < match_count; i++)
2081 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
2087 /* if there was no match, copy to end of string. */
2088 if (!last_match_is_empty)
2090 gchar *token = g_strndup (string + last_separator_end,
2091 match_info->string_len - last_separator_end);
2092 list = g_list_prepend (list, token);
2094 /* no more tokens, end the loop. */
2098 /* -1 to leave room for the last part. */
2099 if (token_count >= max_tokens - 1)
2101 /* we have reached the maximum number of tokens, so we copy
2102 * the remaining part of the string. */
2103 if (last_match_is_empty)
2105 /* the last match was empty, so we have moved one char
2106 * after the real position to avoid empty matches at the
2108 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
2110 /* the if is needed in the case we have terminated the available
2111 * tokens, but we are at the end of the string, so there are no
2112 * characters left to copy. */
2113 if (string_len > match_info->pos)
2115 gchar *token = g_strndup (string + match_info->pos,
2116 string_len - match_info->pos);
2117 list = g_list_prepend (list, token);
2123 last_separator_end = match_info->pos;
2124 if (last_match_is_empty)
2125 /* if the last match was empty, g_match_info_next() has moved
2126 * forward to avoid infinite loops, but we still need to copy that
2128 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
2130 match_ok = g_match_info_next (match_info, &tmp_error);
2132 g_match_info_free (match_info);
2133 if (tmp_error != NULL)
2135 g_propagate_error (error, tmp_error);
2136 g_list_free_full (list, g_free);
2137 match_info->pos = -1;
2141 string_list = g_new (gchar *, g_list_length (list) + 1);
2143 for (last = g_list_last (list); last; last = g_list_previous (last))
2144 string_list[i++] = last->data;
2145 string_list[i] = NULL;
2154 REPL_TYPE_CHARACTER,
2155 REPL_TYPE_SYMBOLIC_REFERENCE,
2156 REPL_TYPE_NUMERIC_REFERENCE,
2157 REPL_TYPE_CHANGE_CASE
2162 CHANGE_CASE_NONE = 1 << 0,
2163 CHANGE_CASE_UPPER = 1 << 1,
2164 CHANGE_CASE_LOWER = 1 << 2,
2165 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
2166 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
2167 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
2168 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
2169 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
2172 struct _InterpolationData
2178 ChangeCase change_case;
2182 free_interpolation_data (InterpolationData *data)
2184 g_free (data->text);
2188 static const gchar *
2189 expand_escape (const gchar *replacement,
2191 InterpolationData *data,
2196 const gchar *error_detail;
2198 GError *tmp_error = NULL;
2206 data->type = REPL_TYPE_CHARACTER;
2211 data->type = REPL_TYPE_CHARACTER;
2216 data->type = REPL_TYPE_CHARACTER;
2221 data->type = REPL_TYPE_CHARACTER;
2226 data->type = REPL_TYPE_CHARACTER;
2231 data->type = REPL_TYPE_CHARACTER;
2236 data->type = REPL_TYPE_CHARACTER;
2241 data->type = REPL_TYPE_CHARACTER;
2251 h = g_ascii_xdigit_value (*p);
2254 error_detail = _("hexadecimal digit or '}' expected");
2265 for (i = 0; i < 2; i++)
2267 h = g_ascii_xdigit_value (*p);
2270 error_detail = _("hexadecimal digit expected");
2277 data->type = REPL_TYPE_STRING;
2278 data->text = g_new0 (gchar, 8);
2279 g_unichar_to_utf8 (x, data->text);
2283 data->type = REPL_TYPE_CHANGE_CASE;
2284 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2288 data->type = REPL_TYPE_CHANGE_CASE;
2289 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2293 data->type = REPL_TYPE_CHANGE_CASE;
2294 data->change_case = CHANGE_CASE_LOWER;
2298 data->type = REPL_TYPE_CHANGE_CASE;
2299 data->change_case = CHANGE_CASE_UPPER;
2303 data->type = REPL_TYPE_CHANGE_CASE;
2304 data->change_case = CHANGE_CASE_NONE;
2310 error_detail = _("missing '<' in symbolic reference");
2319 error_detail = _("unfinished symbolic reference");
2326 error_detail = _("zero-length symbolic reference");
2329 if (g_ascii_isdigit (*q))
2334 h = g_ascii_digit_value (*q);
2337 error_detail = _("digit expected");
2346 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2353 if (!g_ascii_isalnum (*r))
2355 error_detail = _("illegal symbolic reference");
2362 data->text = g_strndup (q, p - q);
2363 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2368 /* if \0 is followed by a number is an octal number representing a
2369 * character, else it is a numeric reference. */
2370 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2373 p = g_utf8_next_char (p);
2386 for (i = 0; i < 3; i++)
2388 h = g_ascii_digit_value (*p);
2398 if (i == 2 && base == 10)
2404 if (base == 8 || i == 3)
2406 data->type = REPL_TYPE_STRING;
2407 data->text = g_new0 (gchar, 8);
2408 g_unichar_to_utf8 (x, data->text);
2412 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2417 error_detail = _("stray final '\\'");
2421 error_detail = _("unknown escape sequence");
2428 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2429 tmp_error = g_error_new (G_REGEX_ERROR,
2430 G_REGEX_ERROR_REPLACE,
2431 _("Error while parsing replacement "
2432 "text \"%s\" at char %lu: %s"),
2434 (gulong)(p - replacement),
2436 g_propagate_error (error, tmp_error);
2442 split_replacement (const gchar *replacement,
2446 InterpolationData *data;
2447 const gchar *p, *start;
2449 start = p = replacement;
2454 data = g_new0 (InterpolationData, 1);
2455 start = p = expand_escape (replacement, p, data, error);
2458 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2459 free_interpolation_data (data);
2463 list = g_list_prepend (list, data);
2468 if (*p == '\\' || *p == '\0')
2472 data = g_new0 (InterpolationData, 1);
2473 data->text = g_strndup (start, p - start);
2474 data->type = REPL_TYPE_STRING;
2475 list = g_list_prepend (list, data);
2481 return g_list_reverse (list);
2484 /* Change the case of c based on change_case. */
2485 #define CHANGE_CASE(c, change_case) \
2486 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2487 g_unichar_tolower (c) : \
2488 g_unichar_toupper (c))
2491 string_append (GString *string,
2493 ChangeCase *change_case)
2497 if (text[0] == '\0')
2500 if (*change_case == CHANGE_CASE_NONE)
2502 g_string_append (string, text);
2504 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2506 c = g_utf8_get_char (text);
2507 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2508 g_string_append (string, g_utf8_next_char (text));
2509 *change_case = CHANGE_CASE_NONE;
2513 while (*text != '\0')
2515 c = g_utf8_get_char (text);
2516 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2517 text = g_utf8_next_char (text);
2523 interpolate_replacement (const GMatchInfo *match_info,
2528 InterpolationData *idata;
2530 ChangeCase change_case = CHANGE_CASE_NONE;
2532 for (list = data; list; list = list->next)
2535 switch (idata->type)
2537 case REPL_TYPE_STRING:
2538 string_append (result, idata->text, &change_case);
2540 case REPL_TYPE_CHARACTER:
2541 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2542 if (change_case & CHANGE_CASE_SINGLE_MASK)
2543 change_case = CHANGE_CASE_NONE;
2545 case REPL_TYPE_NUMERIC_REFERENCE:
2546 match = g_match_info_fetch (match_info, idata->num);
2549 string_append (result, match, &change_case);
2553 case REPL_TYPE_SYMBOLIC_REFERENCE:
2554 match = g_match_info_fetch_named (match_info, idata->text);
2557 string_append (result, match, &change_case);
2561 case REPL_TYPE_CHANGE_CASE:
2562 change_case = idata->change_case;
2570 /* whether actual match_info is needed for replacement, i.e.
2571 * whether there are references
2574 interpolation_list_needs_match (GList *list)
2576 while (list != NULL)
2578 InterpolationData *data = list->data;
2580 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2581 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2594 * @regex: a #GRegex structure
2595 * @string: (array length=string_len): the string to perform matches against
2596 * @string_len: the length of @string, or -1 if @string is nul-terminated
2597 * @start_position: starting index of the string to match
2598 * @replacement: text to replace each match with
2599 * @match_options: options for the match
2600 * @error: location to store the error occurring, or %NULL to ignore errors
2602 * Replaces all occurrences of the pattern in @regex with the
2603 * replacement text. Backreferences of the form '\number' or
2604 * '\g<number>' in the replacement text are interpolated by the
2605 * number-th captured subexpression of the match, '\g<name>' refers
2606 * to the captured subexpression with the given name. '\0' refers to the
2607 * complete match, but '\0' followed by a number is the octal representation
2608 * of a character. To include a literal '\' in the replacement, write '\\'.
2609 * There are also escapes that changes the case of the following text:
2612 * <varlistentry><term>\l</term>
2614 * <para>Convert to lower case the next character</para>
2617 * <varlistentry><term>\u</term>
2619 * <para>Convert to upper case the next character</para>
2622 * <varlistentry><term>\L</term>
2624 * <para>Convert to lower case till \E</para>
2627 * <varlistentry><term>\U</term>
2629 * <para>Convert to upper case till \E</para>
2632 * <varlistentry><term>\E</term>
2634 * <para>End case modification</para>
2639 * If you do not need to use backreferences use g_regex_replace_literal().
2641 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2642 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2643 * you can use g_regex_replace_literal().
2645 * Setting @start_position differs from just passing over a shortened
2646 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2647 * begins with any kind of lookbehind assertion, such as "\b".
2649 * Returns: a newly allocated string containing the replacements
2654 g_regex_replace (const GRegex *regex,
2655 const gchar *string,
2657 gint start_position,
2658 const gchar *replacement,
2659 GRegexMatchFlags match_options,
2664 GError *tmp_error = NULL;
2666 g_return_val_if_fail (regex != NULL, NULL);
2667 g_return_val_if_fail (string != NULL, NULL);
2668 g_return_val_if_fail (start_position >= 0, NULL);
2669 g_return_val_if_fail (replacement != NULL, NULL);
2670 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2671 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2673 list = split_replacement (replacement, &tmp_error);
2674 if (tmp_error != NULL)
2676 g_propagate_error (error, tmp_error);
2680 result = g_regex_replace_eval (regex,
2681 string, string_len, start_position,
2683 interpolate_replacement,
2686 if (tmp_error != NULL)
2687 g_propagate_error (error, tmp_error);
2689 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2695 literal_replacement (const GMatchInfo *match_info,
2699 g_string_append (result, data);
2704 * g_regex_replace_literal:
2705 * @regex: a #GRegex structure
2706 * @string: (array length=string_len): the string to perform matches against
2707 * @string_len: the length of @string, or -1 if @string is nul-terminated
2708 * @start_position: starting index of the string to match
2709 * @replacement: text to replace each match with
2710 * @match_options: options for the match
2711 * @error: location to store the error occurring, or %NULL to ignore errors
2713 * Replaces all occurrences of the pattern in @regex with the
2714 * replacement text. @replacement is replaced literally, to
2715 * include backreferences use g_regex_replace().
2717 * Setting @start_position differs from just passing over a
2718 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2719 * case of a pattern that begins with any kind of lookbehind
2720 * assertion, such as "\b".
2722 * Returns: a newly allocated string containing the replacements
2727 g_regex_replace_literal (const GRegex *regex,
2728 const gchar *string,
2730 gint start_position,
2731 const gchar *replacement,
2732 GRegexMatchFlags match_options,
2735 g_return_val_if_fail (replacement != NULL, NULL);
2736 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2738 return g_regex_replace_eval (regex,
2739 string, string_len, start_position,
2741 literal_replacement,
2742 (gpointer)replacement,
2747 * g_regex_replace_eval:
2748 * @regex: a #GRegex structure from g_regex_new()
2749 * @string: (array length=string_len): string to perform matches against
2750 * @string_len: the length of @string, or -1 if @string is nul-terminated
2751 * @start_position: starting index of the string to match
2752 * @match_options: options for the match
2753 * @eval: a function to call for each match
2754 * @user_data: user data to pass to the function
2755 * @error: location to store the error occurring, or %NULL to ignore errors
2757 * Replaces occurrences of the pattern in regex with the output of
2758 * @eval for that occurrence.
2760 * Setting @start_position differs from just passing over a shortened
2761 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2762 * that begins with any kind of lookbehind assertion, such as "\b".
2764 * The following example uses g_regex_replace_eval() to replace multiple
2768 * eval_cb (const GMatchInfo *info,
2775 * match = g_match_info_fetch (info, 0);
2776 * r = g_hash_table_lookup ((GHashTable *)data, match);
2777 * g_string_append (res, r);
2789 * h = g_hash_table_new (g_str_hash, g_str_equal);
2791 * g_hash_table_insert (h, "1", "ONE");
2792 * g_hash_table_insert (h, "2", "TWO");
2793 * g_hash_table_insert (h, "3", "THREE");
2794 * g_hash_table_insert (h, "4", "FOUR");
2796 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2797 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2798 * g_hash_table_destroy (h);
2803 * Returns: a newly allocated string containing the replacements
2808 g_regex_replace_eval (const GRegex *regex,
2809 const gchar *string,
2811 gint start_position,
2812 GRegexMatchFlags match_options,
2813 GRegexEvalCallback eval,
2817 GMatchInfo *match_info;
2820 gboolean done = FALSE;
2821 GError *tmp_error = NULL;
2823 g_return_val_if_fail (regex != NULL, NULL);
2824 g_return_val_if_fail (string != NULL, NULL);
2825 g_return_val_if_fail (start_position >= 0, NULL);
2826 g_return_val_if_fail (eval != NULL, NULL);
2827 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2830 string_len = strlen (string);
2832 result = g_string_sized_new (string_len);
2834 /* run down the string making matches. */
2835 g_regex_match_full (regex, string, string_len, start_position,
2836 match_options, &match_info, &tmp_error);
2837 while (!done && g_match_info_matches (match_info))
2839 g_string_append_len (result,
2841 match_info->offsets[0] - str_pos);
2842 done = (*eval) (match_info, result, user_data);
2843 str_pos = match_info->offsets[1];
2844 g_match_info_next (match_info, &tmp_error);
2846 g_match_info_free (match_info);
2847 if (tmp_error != NULL)
2849 g_propagate_error (error, tmp_error);
2850 g_string_free (result, TRUE);
2854 g_string_append_len (result, string + str_pos, string_len - str_pos);
2855 return g_string_free (result, FALSE);
2859 * g_regex_check_replacement:
2860 * @replacement: the replacement string
2861 * @has_references: (out) (allow-none): location to store information about
2862 * references in @replacement or %NULL
2863 * @error: location to store error
2865 * Checks whether @replacement is a valid replacement string
2866 * (see g_regex_replace()), i.e. that all escape sequences in
2869 * If @has_references is not %NULL then @replacement is checked
2870 * for pattern references. For instance, replacement text 'foo\n'
2871 * does not contain references and may be evaluated without information
2872 * about actual match, but '\0\1' (whole match followed by first
2873 * subpattern) requires valid #GMatchInfo object.
2875 * Returns: whether @replacement is a valid replacement string
2880 g_regex_check_replacement (const gchar *replacement,
2881 gboolean *has_references,
2887 list = split_replacement (replacement, &tmp);
2891 g_propagate_error (error, tmp);
2896 *has_references = interpolation_list_needs_match (list);
2898 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2904 * g_regex_escape_nul:
2905 * @string: the string to escape
2906 * @length: the length of @string
2908 * Escapes the nul characters in @string to "\x00". It can be used
2909 * to compile a regex with embedded nul characters.
2911 * For completeness, @length can be -1 for a nul-terminated string.
2912 * In this case the output string will be of course equal to @string.
2914 * Returns: a newly-allocated escaped string
2919 g_regex_escape_nul (const gchar *string,
2923 const gchar *p, *piece_start, *end;
2926 g_return_val_if_fail (string != NULL, NULL);
2929 return g_strdup (string);
2931 end = string + length;
2932 p = piece_start = string;
2933 escaped = g_string_sized_new (length + 1);
2941 if (p != piece_start)
2943 /* copy the previous piece. */
2944 g_string_append_len (escaped, piece_start, p - piece_start);
2946 if ((backslashes & 1) == 0)
2947 g_string_append_c (escaped, '\\');
2948 g_string_append_c (escaped, 'x');
2949 g_string_append_c (escaped, '0');
2950 g_string_append_c (escaped, '0');
2960 p = g_utf8_next_char (p);
2965 if (piece_start < end)
2966 g_string_append_len (escaped, piece_start, end - piece_start);
2968 return g_string_free (escaped, FALSE);
2972 * g_regex_escape_string:
2973 * @string: (array length=length): the string to escape
2974 * @length: the length of @string, or -1 if @string is nul-terminated
2976 * Escapes the special characters used for regular expressions
2977 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2978 * function is useful to dynamically generate regular expressions.
2980 * @string can contain nul characters that are replaced with "\0",
2981 * in this case remember to specify the correct length of @string
2984 * Returns: a newly-allocated escaped string
2989 g_regex_escape_string (const gchar *string,
2993 const char *p, *piece_start, *end;
2995 g_return_val_if_fail (string != NULL, NULL);
2998 length = strlen (string);
3000 end = string + length;
3001 p = piece_start = string;
3002 escaped = g_string_sized_new (length + 1);
3023 if (p != piece_start)
3024 /* copy the previous piece. */
3025 g_string_append_len (escaped, piece_start, p - piece_start);
3026 g_string_append_c (escaped, '\\');
3028 g_string_append_c (escaped, '0');
3030 g_string_append_c (escaped, *p);
3034 p = g_utf8_next_char (p);
3039 if (piece_start < end)
3040 g_string_append_len (escaped, piece_start, end - piece_start);
3042 return g_string_free (escaped, FALSE);