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)
118 /* Mask of all the possible values for GRegexMatchFlags. */
119 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
120 G_REGEX_MATCH_NOTBOL | \
121 G_REGEX_MATCH_NOTEOL | \
122 G_REGEX_MATCH_NOTEMPTY | \
123 G_REGEX_MATCH_PARTIAL | \
124 G_REGEX_MATCH_NEWLINE_CR | \
125 G_REGEX_MATCH_NEWLINE_LF | \
126 G_REGEX_MATCH_NEWLINE_CRLF | \
127 G_REGEX_MATCH_NEWLINE_ANY | \
128 G_REGEX_MATCH_NEWLINE_ANYCRLF)
130 /* we rely on these flags having the same values */
131 G_STATIC_ASSERT (G_REGEX_CASELESS == PCRE_CASELESS);
132 G_STATIC_ASSERT (G_REGEX_MULTILINE == PCRE_MULTILINE);
133 G_STATIC_ASSERT (G_REGEX_DOTALL == PCRE_DOTALL);
134 G_STATIC_ASSERT (G_REGEX_EXTENDED == PCRE_EXTENDED);
135 G_STATIC_ASSERT (G_REGEX_ANCHORED == PCRE_ANCHORED);
136 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY == PCRE_DOLLAR_ENDONLY);
137 G_STATIC_ASSERT (G_REGEX_UNGREEDY == PCRE_UNGREEDY);
138 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE == PCRE_NO_AUTO_CAPTURE);
139 G_STATIC_ASSERT (G_REGEX_DUPNAMES == PCRE_DUPNAMES);
140 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR == PCRE_NEWLINE_CR);
141 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF == PCRE_NEWLINE_LF);
142 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
143 G_STATIC_ASSERT (G_REGEX_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
145 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED == PCRE_ANCHORED);
146 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL == PCRE_NOTBOL);
147 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL == PCRE_NOTEOL);
148 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY == PCRE_NOTEMPTY);
149 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL == PCRE_PARTIAL);
150 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR == PCRE_NEWLINE_CR);
151 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF == PCRE_NEWLINE_LF);
152 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF == PCRE_NEWLINE_CRLF);
153 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY == PCRE_NEWLINE_ANY);
154 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANYCRLF == PCRE_NEWLINE_ANYCRLF);
156 /* if the string is in UTF-8 use g_utf8_ functions, else use
158 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
159 g_utf8_next_char (s) : \
161 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
162 g_utf8_prev_char (s) : \
167 volatile gint ref_count; /* the ref count */
168 GRegex *regex; /* the regex */
169 GRegexMatchFlags match_opts; /* options used at match time on the regex */
170 gint matches; /* number of matching sub patterns */
171 gint pos; /* position in the string where last match left off */
172 gint n_offsets; /* number of offsets */
173 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
174 gint *workspace; /* workspace for pcre_dfa_exec() */
175 gint n_workspace; /* number of workspace elements */
176 const gchar *string; /* string passed to the match function */
177 gssize string_len; /* length of string */
182 volatile gint ref_count; /* the ref count for the immutable part */
183 gchar *pattern; /* the pattern */
184 pcre *pcre_re; /* compiled form of the pattern */
185 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
186 GRegexMatchFlags match_opts; /* options used at match time on the regex */
187 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
190 /* TRUE if ret is an error code, FALSE otherwise. */
191 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
193 typedef struct _InterpolationData InterpolationData;
194 static gboolean interpolation_list_needs_match (GList *list);
195 static gboolean interpolate_replacement (const GMatchInfo *match_info,
198 static GList *split_replacement (const gchar *replacement,
200 static void free_interpolation_data (InterpolationData *data);
204 match_error (gint errcode)
208 case PCRE_ERROR_NOMATCH:
211 case PCRE_ERROR_NULL:
212 /* NULL argument, this should not happen in GRegex */
213 g_warning ("A NULL argument was passed to PCRE");
215 case PCRE_ERROR_BADOPTION:
216 return "bad options";
217 case PCRE_ERROR_BADMAGIC:
218 return _("corrupted object");
219 case PCRE_ERROR_UNKNOWN_OPCODE:
220 return N_("internal error or corrupted object");
221 case PCRE_ERROR_NOMEMORY:
222 return _("out of memory");
223 case PCRE_ERROR_NOSUBSTRING:
224 /* not used by pcre_exec() */
226 case PCRE_ERROR_MATCHLIMIT:
227 return _("backtracking limit reached");
228 case PCRE_ERROR_CALLOUT:
229 /* callouts are not implemented */
231 case PCRE_ERROR_BADUTF8:
232 case PCRE_ERROR_BADUTF8_OFFSET:
233 /* we do not check if strings are valid */
235 case PCRE_ERROR_PARTIAL:
238 case PCRE_ERROR_BADPARTIAL:
239 return _("the pattern contains items not supported for partial matching");
240 case PCRE_ERROR_INTERNAL:
241 return _("internal error");
242 case PCRE_ERROR_BADCOUNT:
243 /* negative ovecsize, this should not happen in GRegex */
244 g_warning ("A negative ovecsize was passed to PCRE");
246 case PCRE_ERROR_DFA_UITEM:
247 return _("the pattern contains items not supported for partial matching");
248 case PCRE_ERROR_DFA_UCOND:
249 return _("back references as conditions are not supported for partial matching");
250 case PCRE_ERROR_DFA_UMLIMIT:
251 /* the match_field field is not used in GRegex */
253 case PCRE_ERROR_DFA_WSSIZE:
254 /* handled expanding the workspace */
256 case PCRE_ERROR_DFA_RECURSE:
257 case PCRE_ERROR_RECURSIONLIMIT:
258 return _("recursion limit reached");
259 case PCRE_ERROR_BADNEWLINE:
260 return _("invalid combination of newline flags");
261 case PCRE_ERROR_BADOFFSET:
262 return _("bad offset");
263 case PCRE_ERROR_SHORTUTF8:
264 return _("short utf8");
265 case PCRE_ERROR_RECURSELOOP:
266 return _("recursion loop");
270 return _("unknown error");
274 translate_compile_error (gint *errcode, const gchar **errmsg)
276 /* Compile errors are created adding 100 to the error code returned
278 * If errcode is known we put the translatable error message in
279 * erromsg. If errcode is unknown we put the generic
280 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
281 * untranslated error message returned by PCRE.
282 * Note that there can be more PCRE errors with the same GRegexError
283 * and that some PCRE errors are useless for us.
289 case G_REGEX_ERROR_STRAY_BACKSLASH:
290 *errmsg = _("\\ at end of pattern");
292 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
293 *errmsg = _("\\c at end of pattern");
295 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
296 *errmsg = _("unrecognized character follows \\");
298 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
299 *errmsg = _("numbers out of order in {} quantifier");
301 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
302 *errmsg = _("number too big in {} quantifier");
304 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
305 *errmsg = _("missing terminating ] for character class");
307 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
308 *errmsg = _("invalid escape sequence in character class");
310 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
311 *errmsg = _("range out of order in character class");
313 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
314 *errmsg = _("nothing to repeat");
316 case 111: /* internal error: unexpected repeat */
317 *errcode = G_REGEX_ERROR_INTERNAL;
318 *errmsg = _("unexpected repeat");
320 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
321 *errmsg = _("unrecognized character after (? or (?-");
323 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
324 *errmsg = _("POSIX named classes are supported only within a class");
326 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
327 *errmsg = _("missing terminating )");
329 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
330 *errmsg = _("reference to non-existent subpattern");
332 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
333 *errmsg = _("missing ) after comment");
335 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
336 *errmsg = _("regular expression is too large");
338 case G_REGEX_ERROR_MEMORY_ERROR:
339 *errmsg = _("failed to get memory");
341 case 122: /* unmatched parentheses */
342 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
343 *errmsg = _(") without opening (");
345 case 123: /* internal error: code overflow */
346 *errcode = G_REGEX_ERROR_INTERNAL;
347 *errmsg = _("code overflow");
349 case 124: /* "unrecognized character after (?<\0 */
350 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
351 *errmsg = _("unrecognized character after (?<");
353 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
354 *errmsg = _("lookbehind assertion is not fixed length");
356 case G_REGEX_ERROR_MALFORMED_CONDITION:
357 *errmsg = _("malformed number or name after (?(");
359 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
360 *errmsg = _("conditional group contains more than two branches");
362 case G_REGEX_ERROR_ASSERTION_EXPECTED:
363 *errmsg = _("assertion expected after (?(");
366 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
367 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
368 * sequences here, '(?-54' would be an example for the second group.
370 *errmsg = _("(?R or (?[+-]digits must be followed by )");
372 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
373 *errmsg = _("unknown POSIX class name");
375 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
376 *errmsg = _("POSIX collating elements are not supported");
378 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
379 *errmsg = _("character value in \\x{...} sequence is too large");
381 case G_REGEX_ERROR_INVALID_CONDITION:
382 *errmsg = _("invalid condition (?(0)");
384 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
385 *errmsg = _("\\C not allowed in lookbehind assertion");
387 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
388 /* A number of Perl escapes are not handled by PCRE.
389 * Therefore it explicitly raises ERR37.
391 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
392 *errmsg = _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
394 case G_REGEX_ERROR_INFINITE_LOOP:
395 *errmsg = _("recursive call could loop indefinitely");
397 case 141: /* unrecognized character after (?P\0 */
398 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
399 *errmsg = _("unrecognized character after (?P");
401 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
402 *errmsg = _("missing terminator in subpattern name");
404 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
405 *errmsg = _("two named subpatterns have the same name");
407 case G_REGEX_ERROR_MALFORMED_PROPERTY:
408 *errmsg = _("malformed \\P or \\p sequence");
410 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
411 *errmsg = _("unknown property name after \\P or \\p");
413 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
414 *errmsg = _("subpattern name is too long (maximum 32 characters)");
416 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
417 *errmsg = _("too many named subpatterns (maximum 10,000)");
419 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
420 *errmsg = _("octal value is greater than \\377");
422 case 152: /* internal error: overran compiling workspace */
423 *errcode = G_REGEX_ERROR_INTERNAL;
424 *errmsg = _("overran compiling workspace");
426 case 153: /* internal error: previously-checked referenced subpattern not found */
427 *errcode = G_REGEX_ERROR_INTERNAL;
428 *errmsg = _("previously-checked referenced subpattern not found");
430 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
431 *errmsg = _("DEFINE group contains more than one branch");
433 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
434 *errmsg = _("inconsistent NEWLINE options");
436 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
437 *errmsg = _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
438 "number, or by a plain number");
440 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE:
441 *errmsg = _("a numbered reference must not be zero");
443 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
444 *errmsg = _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
446 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB:
447 *errmsg = _("(*VERB) not recognized");
449 case G_REGEX_ERROR_NUMBER_TOO_BIG:
450 *errmsg = _("number is too bug");
452 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME:
453 *errmsg = _("missing subpattern name after (?&");
455 case G_REGEX_ERROR_MISSING_DIGIT:
456 *errmsg = _("digit expected after (?+");
458 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME:
459 *errmsg = _("different names for subpatterns of the same number are not allowed");
461 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
462 *errmsg = _("(*MARK) must have an argument");
464 case G_REGEX_ERROR_INVALID_CONTROL_CHAR:
465 *errmsg = _( "\\c must be followed by an ASCII character");
467 case G_REGEX_ERROR_MISSING_NAME:
468 *errmsg = _("\\k is not followed by a braced, angle-bracketed, or quoted name");
470 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS:
471 *errmsg = _("\\N is not supported in a class");
473 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES:
474 *errmsg = _("too many forward references");
476 case G_REGEX_ERROR_NAME_TOO_LONG:
477 *errmsg = _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
480 case 116: /* erroffset passed as NULL */
481 /* This should not happen as we never pass a NULL erroffset */
482 g_warning ("erroffset passed as NULL");
483 *errcode = G_REGEX_ERROR_COMPILE;
485 case 117: /* unknown option bit(s) set */
486 /* This should not happen as we check options before passing them
487 * to pcre_compile2() */
488 g_warning ("unknown option bit(s) set");
489 *errcode = G_REGEX_ERROR_COMPILE;
491 case 132: /* this version of PCRE is compiled without UTF support */
492 case 144: /* invalid UTF-8 string */
493 case 145: /* support for \\P, \\p, and \\X has not been compiled */
494 case 167: /* this version of PCRE is not compiled with Unicode property support */
495 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
496 case 174: /* invalid UTF-16 string */
497 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
498 * and we do not check if strings are valid */
499 case 164: /* ] is an invalid data character in JavaScript compatibility mode */
500 /* This should not happen as we don't use PCRE_JAVASCRIPT_COMPAT */
501 g_warning ("%s", *errmsg);
502 *errcode = G_REGEX_ERROR_COMPILE;
504 case 170: /* internal error: unknown opcode in find_fixedlength() */
505 *errcode = G_REGEX_ERROR_INTERNAL;
509 *errcode = G_REGEX_ERROR_COMPILE;
516 match_info_new (const GRegex *regex,
523 GMatchInfo *match_info;
526 string_len = strlen (string);
528 match_info = g_new0 (GMatchInfo, 1);
529 match_info->ref_count = 1;
530 match_info->regex = g_regex_ref ((GRegex *)regex);
531 match_info->string = string;
532 match_info->string_len = string_len;
533 match_info->matches = PCRE_ERROR_NOMATCH;
534 match_info->pos = start_position;
535 match_info->match_opts = match_options;
539 /* These values should be enough for most cases, if they are not
540 * enough g_regex_match_all_full() will expand them. */
541 match_info->n_offsets = 24;
542 match_info->n_workspace = 100;
543 match_info->workspace = g_new (gint, match_info->n_workspace);
548 pcre_fullinfo (regex->pcre_re, regex->extra,
549 PCRE_INFO_CAPTURECOUNT, &capture_count);
550 match_info->n_offsets = (capture_count + 1) * 3;
553 match_info->offsets = g_new0 (gint, match_info->n_offsets);
554 /* Set an invalid position for the previous match. */
555 match_info->offsets[0] = -1;
556 match_info->offsets[1] = -1;
562 * g_match_info_get_regex:
563 * @match_info: a #GMatchInfo
565 * Returns #GRegex object used in @match_info. It belongs to Glib
566 * and must not be freed. Use g_regex_ref() if you need to keep it
567 * after you free @match_info object.
569 * Returns: #GRegex object used in @match_info
574 g_match_info_get_regex (const GMatchInfo *match_info)
576 g_return_val_if_fail (match_info != NULL, NULL);
577 return match_info->regex;
581 * g_match_info_get_string:
582 * @match_info: a #GMatchInfo
584 * Returns the string searched with @match_info. This is the
585 * string passed to g_regex_match() or g_regex_replace() so
586 * you may not free it before calling this function.
588 * Returns: the string searched with @match_info
593 g_match_info_get_string (const GMatchInfo *match_info)
595 g_return_val_if_fail (match_info != NULL, NULL);
596 return match_info->string;
601 * @match_info: a #GMatchInfo
603 * Increases reference count of @match_info by 1.
605 * Returns: @match_info
610 g_match_info_ref (GMatchInfo *match_info)
612 g_return_val_if_fail (match_info != NULL, NULL);
613 g_atomic_int_inc (&match_info->ref_count);
618 * g_match_info_unref:
619 * @match_info: a #GMatchInfo
621 * Decreases reference count of @match_info by 1. When reference count drops
622 * to zero, it frees all the memory associated with the match_info structure.
627 g_match_info_unref (GMatchInfo *match_info)
629 if (g_atomic_int_dec_and_test (&match_info->ref_count))
631 g_regex_unref (match_info->regex);
632 g_free (match_info->offsets);
633 g_free (match_info->workspace);
640 * @match_info: (allow-none): a #GMatchInfo, or %NULL
642 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
648 g_match_info_free (GMatchInfo *match_info)
650 if (match_info == NULL)
653 g_match_info_unref (match_info);
658 * @match_info: a #GMatchInfo structure
659 * @error: location to store the error occurring, or %NULL to ignore errors
661 * Scans for the next match using the same parameters of the previous
662 * call to g_regex_match_full() or g_regex_match() that returned
665 * The match is done on the string passed to the match function, so you
666 * cannot free it before calling this function.
668 * Returns: %TRUE is the string matched, %FALSE otherwise
673 g_match_info_next (GMatchInfo *match_info,
676 gint prev_match_start;
679 g_return_val_if_fail (match_info != NULL, FALSE);
680 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
681 g_return_val_if_fail (match_info->pos >= 0, FALSE);
683 prev_match_start = match_info->offsets[0];
684 prev_match_end = match_info->offsets[1];
686 if (match_info->pos > match_info->string_len)
688 /* we have reached the end of the string */
689 match_info->pos = -1;
690 match_info->matches = PCRE_ERROR_NOMATCH;
694 match_info->matches = pcre_exec (match_info->regex->pcre_re,
695 match_info->regex->extra,
697 match_info->string_len,
699 match_info->regex->match_opts | match_info->match_opts,
701 match_info->n_offsets);
702 if (IS_PCRE_ERROR (match_info->matches))
704 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
705 _("Error while matching regular expression %s: %s"),
706 match_info->regex->pattern, match_error (match_info->matches));
710 /* avoid infinite loops if the pattern is an empty string or something
712 if (match_info->pos == match_info->offsets[1])
714 if (match_info->pos > match_info->string_len)
716 /* we have reached the end of the string */
717 match_info->pos = -1;
718 match_info->matches = PCRE_ERROR_NOMATCH;
722 match_info->pos = NEXT_CHAR (match_info->regex,
723 &match_info->string[match_info->pos]) -
728 match_info->pos = match_info->offsets[1];
731 /* it's possible to get two identical matches when we are matching
732 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
733 * the string is "RegExTest" we have:
734 * - search at position 0: match from 0 to 0
735 * - search at position 1: match from 3 to 3
736 * - search at position 3: match from 3 to 3 (duplicate)
737 * - search at position 4: match from 5 to 5
738 * - search at position 5: match from 5 to 5 (duplicate)
739 * - search at position 6: no match -> stop
740 * so we have to ignore the duplicates.
741 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
742 if (match_info->matches >= 0 &&
743 prev_match_start == match_info->offsets[0] &&
744 prev_match_end == match_info->offsets[1])
746 /* ignore this match and search the next one */
747 return g_match_info_next (match_info, error);
750 return match_info->matches >= 0;
754 * g_match_info_matches:
755 * @match_info: a #GMatchInfo structure
757 * Returns whether the previous match operation succeeded.
759 * Returns: %TRUE if the previous match operation succeeded,
765 g_match_info_matches (const GMatchInfo *match_info)
767 g_return_val_if_fail (match_info != NULL, FALSE);
769 return match_info->matches >= 0;
773 * g_match_info_get_match_count:
774 * @match_info: a #GMatchInfo structure
776 * Retrieves the number of matched substrings (including substring 0,
777 * that is the whole matched text), so 1 is returned if the pattern
778 * has no substrings in it and 0 is returned if the match failed.
780 * If the last match was obtained using the DFA algorithm, that is
781 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
782 * count is not that of the number of capturing parentheses but that of
783 * the number of matched substrings.
785 * Returns: Number of matched substrings, or -1 if an error occurred
790 g_match_info_get_match_count (const GMatchInfo *match_info)
792 g_return_val_if_fail (match_info, -1);
794 if (match_info->matches == PCRE_ERROR_NOMATCH)
797 else if (match_info->matches < PCRE_ERROR_NOMATCH)
802 return match_info->matches;
806 * g_match_info_is_partial_match:
807 * @match_info: a #GMatchInfo structure
809 * Usually if the string passed to g_regex_match*() matches as far as
810 * it goes, but is too short to match the entire pattern, %FALSE is
811 * returned. There are circumstances where it might be helpful to
812 * distinguish this case from other cases in which there is no match.
814 * Consider, for example, an application where a human is required to
815 * type in data for a field with specific formatting requirements. An
816 * example might be a date in the form ddmmmyy, defined by the pattern
817 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
818 * If the application sees the user’s keystrokes one by one, and can
819 * check that what has been typed so far is potentially valid, it is
820 * able to raise an error as soon as a mistake is made.
822 * GRegex supports the concept of partial matching by means of the
823 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
824 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
825 * for a complete match, %FALSE otherwise. But, when these functions
826 * return %FALSE, you can check if the match was partial calling
827 * g_match_info_is_partial_match().
829 * When using partial matching you cannot use g_match_info_fetch*().
831 * Because of the way certain internal optimizations are implemented
832 * the partial matching algorithm cannot be used with all patterns.
833 * So repeated single characters such as "a{2,4}" and repeated single
834 * meta-sequences such as "\d+" are not permitted if the maximum number
835 * of occurrences is greater than one. Optional items such as "\d?"
836 * (where the maximum is one) are permitted. Quantifiers with any values
837 * are permitted after parentheses, so the invalid examples above can be
838 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
839 * for a pattern that does not conform to the restrictions, matching
840 * functions return an error.
842 * Returns: %TRUE if the match was partial, %FALSE otherwise
847 g_match_info_is_partial_match (const GMatchInfo *match_info)
849 g_return_val_if_fail (match_info != NULL, FALSE);
851 return match_info->matches == PCRE_ERROR_PARTIAL;
855 * g_match_info_expand_references:
856 * @match_info: (allow-none): a #GMatchInfo or %NULL
857 * @string_to_expand: the string to expand
858 * @error: location to store the error occurring, or %NULL to ignore errors
860 * Returns a new string containing the text in @string_to_expand with
861 * references and escape sequences expanded. References refer to the last
862 * match done with @string against @regex and have the same syntax used by
865 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
866 * passed to g_regex_new().
868 * The backreferences are extracted from the string passed to the match
869 * function, so you cannot call this function after freeing the string.
871 * @match_info may be %NULL in which case @string_to_expand must not
872 * contain references. For instance "foo\n" does not refer to an actual
873 * pattern and '\n' merely will be replaced with \n character,
874 * while to expand "\0" (whole match) one needs the result of a match.
875 * Use g_regex_check_replacement() to find out whether @string_to_expand
876 * contains references.
878 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
883 g_match_info_expand_references (const GMatchInfo *match_info,
884 const gchar *string_to_expand,
889 GError *tmp_error = NULL;
891 g_return_val_if_fail (string_to_expand != NULL, NULL);
892 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
894 list = split_replacement (string_to_expand, &tmp_error);
895 if (tmp_error != NULL)
897 g_propagate_error (error, tmp_error);
901 if (!match_info && interpolation_list_needs_match (list))
903 g_critical ("String '%s' contains references to the match, can't "
904 "expand references without GMatchInfo object",
909 result = g_string_sized_new (strlen (string_to_expand));
910 interpolate_replacement (match_info, result, list);
912 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
914 return g_string_free (result, FALSE);
918 * g_match_info_fetch:
919 * @match_info: #GMatchInfo structure
920 * @match_num: number of the sub expression
922 * Retrieves the text matching the @match_num<!-- -->'th capturing
923 * parentheses. 0 is the full text of the match, 1 is the first paren
924 * set, 2 the second, and so on.
926 * If @match_num is a valid sub pattern but it didn't match anything
927 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
928 * string is returned.
930 * If the match was obtained using the DFA algorithm, that is using
931 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
932 * string is not that of a set of parentheses but that of a matched
933 * substring. Substrings are matched in reverse order of length, so
934 * 0 is the longest match.
936 * The string is fetched from the string passed to the match function,
937 * so you cannot call this function after freeing the string.
939 * Returns: (allow-none): The matched substring, or %NULL if an error
940 * occurred. You have to free the string yourself
945 g_match_info_fetch (const GMatchInfo *match_info,
948 /* we cannot use pcre_get_substring() because it allocates the
949 * string using pcre_malloc(). */
953 g_return_val_if_fail (match_info != NULL, NULL);
954 g_return_val_if_fail (match_num >= 0, NULL);
956 /* match_num does not exist or it didn't matched, i.e. matching "b"
957 * against "(a)?b" then group 0 is empty. */
958 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
960 else if (start == -1)
961 match = g_strdup ("");
963 match = g_strndup (&match_info->string[start], end - start);
969 * g_match_info_fetch_pos:
970 * @match_info: #GMatchInfo structure
971 * @match_num: number of the sub expression
972 * @start_pos: (out) (allow-none): pointer to location where to store
973 * the start position, or %NULL
974 * @end_pos: (out) (allow-none): pointer to location where to store
975 * the end position, or %NULL
977 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
978 * parentheses. 0 is the full text of the match, 1 is the first
979 * paren set, 2 the second, and so on.
981 * If @match_num is a valid sub pattern but it didn't match anything
982 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
983 * and @end_pos are set to -1 and %TRUE is returned.
985 * If the match was obtained using the DFA algorithm, that is using
986 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
987 * position is not that of a set of parentheses but that of a matched
988 * substring. Substrings are matched in reverse order of length, so
989 * 0 is the longest match.
991 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
992 * the position cannot be fetched, @start_pos and @end_pos are left
998 g_match_info_fetch_pos (const GMatchInfo *match_info,
1003 g_return_val_if_fail (match_info != NULL, FALSE);
1004 g_return_val_if_fail (match_num >= 0, FALSE);
1006 /* make sure the sub expression number they're requesting is less than
1007 * the total number of sub expressions that were matched. */
1008 if (match_num >= match_info->matches)
1011 if (start_pos != NULL)
1012 *start_pos = match_info->offsets[2 * match_num];
1014 if (end_pos != NULL)
1015 *end_pos = match_info->offsets[2 * match_num + 1];
1021 * Returns number of first matched subpattern with name @name.
1022 * There may be more than one in case when DUPNAMES is used,
1023 * and not all subpatterns with that name match;
1024 * pcre_get_stringnumber() does not work in that case.
1027 get_matched_substring_number (const GMatchInfo *match_info,
1031 gchar *first, *last;
1034 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
1035 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
1037 /* This code is copied from pcre_get.c: get_first_set() */
1038 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
1046 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
1048 gint n = (entry[0] << 8) + entry[1];
1049 if (match_info->offsets[n*2] >= 0)
1053 return (first[0] << 8) + first[1];
1057 * g_match_info_fetch_named:
1058 * @match_info: #GMatchInfo structure
1059 * @name: name of the subexpression
1061 * Retrieves the text matching the capturing parentheses named @name.
1063 * If @name is a valid sub pattern name but it didn't match anything
1064 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1065 * then an empty string is returned.
1067 * The string is fetched from the string passed to the match function,
1068 * so you cannot call this function after freeing the string.
1070 * Returns: (allow-none): The matched substring, or %NULL if an error
1071 * occurred. You have to free the string yourself
1076 g_match_info_fetch_named (const GMatchInfo *match_info,
1079 /* we cannot use pcre_get_named_substring() because it allocates the
1080 * string using pcre_malloc(). */
1083 g_return_val_if_fail (match_info != NULL, NULL);
1084 g_return_val_if_fail (name != NULL, NULL);
1086 num = get_matched_substring_number (match_info, name);
1090 return g_match_info_fetch (match_info, num);
1094 * g_match_info_fetch_named_pos:
1095 * @match_info: #GMatchInfo structure
1096 * @name: name of the subexpression
1097 * @start_pos: (out) (allow-none): pointer to location where to store
1098 * the start position, or %NULL
1099 * @end_pos: (out) (allow-none): pointer to location where to store
1100 * the end position, or %NULL
1102 * Retrieves the position in bytes of the capturing parentheses named @name.
1104 * If @name is a valid sub pattern name but it didn't match anything
1105 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1106 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1108 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1109 * If the position cannot be fetched, @start_pos and @end_pos
1110 * are left unchanged.
1115 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
1122 g_return_val_if_fail (match_info != NULL, FALSE);
1123 g_return_val_if_fail (name != NULL, FALSE);
1125 num = get_matched_substring_number (match_info, name);
1129 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
1133 * g_match_info_fetch_all:
1134 * @match_info: a #GMatchInfo structure
1136 * Bundles up pointers to each of the matching substrings from a match
1137 * and stores them in an array of gchar pointers. The first element in
1138 * the returned array is the match number 0, i.e. the entire matched
1141 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1142 * "b" against "(a)?b") then an empty string is inserted.
1144 * If the last match was obtained using the DFA algorithm, that is using
1145 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1146 * strings are not that matched by sets of parentheses but that of the
1147 * matched substring. Substrings are matched in reverse order of length,
1148 * so the first one is the longest match.
1150 * The strings are fetched from the string passed to the match function,
1151 * so you cannot call this function after freeing the string.
1153 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
1154 * It must be freed using g_strfreev(). If the previous match failed
1160 g_match_info_fetch_all (const GMatchInfo *match_info)
1162 /* we cannot use pcre_get_substring_list() because the returned value
1163 * isn't suitable for g_strfreev(). */
1167 g_return_val_if_fail (match_info != NULL, NULL);
1169 if (match_info->matches < 0)
1172 result = g_new (gchar *, match_info->matches + 1);
1173 for (i = 0; i < match_info->matches; i++)
1174 result[i] = g_match_info_fetch (match_info, i);
1184 g_regex_error_quark (void)
1186 static GQuark error_quark = 0;
1188 if (error_quark == 0)
1189 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1198 * Increases reference count of @regex by 1.
1205 g_regex_ref (GRegex *regex)
1207 g_return_val_if_fail (regex != NULL, NULL);
1208 g_atomic_int_inc (®ex->ref_count);
1216 * Decreases reference count of @regex by 1. When reference count drops
1217 * to zero, it frees all the memory associated with the regex structure.
1222 g_regex_unref (GRegex *regex)
1224 g_return_if_fail (regex != NULL);
1226 if (g_atomic_int_dec_and_test (®ex->ref_count))
1228 g_free (regex->pattern);
1229 if (regex->pcre_re != NULL)
1230 pcre_free (regex->pcre_re);
1231 if (regex->extra != NULL)
1232 pcre_free (regex->extra);
1239 * @pattern: the regular expression
1240 * @compile_options: compile options for the regular expression, or 0
1241 * @match_options: match options for the regular expression, or 0
1242 * @error: return location for a #GError
1244 * Compiles the regular expression to an internal form, and does
1245 * the initial setup of the #GRegex structure.
1247 * Returns: a #GRegex structure. Call g_regex_unref() when you
1253 g_regex_new (const gchar *pattern,
1254 GRegexCompileFlags compile_options,
1255 GRegexMatchFlags match_options,
1260 const gchar *errmsg;
1263 gboolean optimize = FALSE;
1264 static gsize initialised;
1265 unsigned long int pcre_compile_options;
1267 g_return_val_if_fail (pattern != NULL, NULL);
1268 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1269 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1270 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1272 if (g_once_init_enter (&initialised))
1277 pcre_config (PCRE_CONFIG_UTF8, &support);
1280 msg = N_("PCRE library is compiled without UTF8 support");
1281 g_critical ("%s", msg);
1282 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1286 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
1289 msg = N_("PCRE library is compiled without UTF8 properties support");
1290 g_critical ("%s", msg);
1291 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1295 g_once_init_leave (&initialised, TRUE);
1298 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1299 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1300 if (compile_options & G_REGEX_OPTIMIZE)
1303 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1304 * instead uses UTF-8 only if required with PCRE_UTF8. */
1305 if (compile_options & G_REGEX_RAW)
1308 compile_options &= ~G_REGEX_RAW;
1313 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1314 match_options |= PCRE_NO_UTF8_CHECK;
1317 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1318 * not for the system one. */
1319 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1320 !(compile_options & G_REGEX_NEWLINE_LF))
1322 compile_options |= PCRE_NEWLINE_ANY;
1325 compile_options |= PCRE_UCP;
1327 /* compile the pattern */
1328 re = pcre_compile2 (pattern, compile_options, &errcode,
1329 &errmsg, &erroffset, NULL);
1331 /* if the compilation failed, set the error member and return
1337 /* Translate the PCRE error code to GRegexError and use a translated
1338 * error message if possible */
1339 translate_compile_error (&errcode, &errmsg);
1341 /* PCRE uses byte offsets but we want to show character offsets */
1342 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1344 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1345 _("Error while compiling regular "
1346 "expression %s at char %d: %s"),
1347 pattern, erroffset, errmsg);
1348 g_propagate_error (error, tmp_error);
1353 /* For options set at the beginning of the pattern, pcre puts them into
1354 * compile options, e.g. "(?i)foo" will make the pcre structure store
1355 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1356 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1357 compile_options = pcre_compile_options;
1359 if (!(compile_options & G_REGEX_DUPNAMES))
1361 gboolean jchanged = FALSE;
1362 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1364 compile_options |= G_REGEX_DUPNAMES;
1367 regex = g_new0 (GRegex, 1);
1368 regex->ref_count = 1;
1369 regex->pattern = g_strdup (pattern);
1370 regex->pcre_re = re;
1371 regex->compile_opts = compile_options;
1372 regex->match_opts = match_options;
1376 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1379 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1380 G_REGEX_ERROR_OPTIMIZE,
1381 _("Error while optimizing "
1382 "regular expression %s: %s"),
1385 g_propagate_error (error, tmp_error);
1387 g_regex_unref (regex);
1396 * g_regex_get_pattern:
1397 * @regex: a #GRegex structure
1399 * Gets the pattern string associated with @regex, i.e. a copy of
1400 * the string passed to g_regex_new().
1402 * Returns: the pattern of @regex
1407 g_regex_get_pattern (const GRegex *regex)
1409 g_return_val_if_fail (regex != NULL, NULL);
1411 return regex->pattern;
1415 * g_regex_get_max_backref:
1418 * Returns the number of the highest back reference
1419 * in the pattern, or 0 if the pattern does not contain
1422 * Returns: the number of the highest back reference
1427 g_regex_get_max_backref (const GRegex *regex)
1431 pcre_fullinfo (regex->pcre_re, regex->extra,
1432 PCRE_INFO_BACKREFMAX, &value);
1438 * g_regex_get_capture_count:
1441 * Returns the number of capturing subpatterns in the pattern.
1443 * Returns: the number of capturing subpatterns
1448 g_regex_get_capture_count (const GRegex *regex)
1452 pcre_fullinfo (regex->pcre_re, regex->extra,
1453 PCRE_INFO_CAPTURECOUNT, &value);
1459 * g_regex_get_has_cr_or_lf:
1460 * @regex: a #GRegex structure
1462 * Checks whether the pattern contains explicit CR or LF references.
1464 * Returns: %TRUE if the pattern contains explicit CR or LF references
1469 g_regex_get_has_cr_or_lf (const GRegex *regex)
1473 pcre_fullinfo (regex->pcre_re, regex->extra,
1474 PCRE_INFO_HASCRORLF, &value);
1480 * g_regex_get_compile_flags:
1483 * Returns the compile options that @regex was created with.
1485 * Returns: flags from #GRegexCompileFlags
1490 g_regex_get_compile_flags (const GRegex *regex)
1492 g_return_val_if_fail (regex != NULL, 0);
1494 return regex->compile_opts;
1498 * g_regex_get_match_flags:
1501 * Returns the match options that @regex was created with.
1503 * Returns: flags from #GRegexMatchFlags
1508 g_regex_get_match_flags (const GRegex *regex)
1510 g_return_val_if_fail (regex != NULL, 0);
1512 return regex->match_opts;
1516 * g_regex_match_simple:
1517 * @pattern: the regular expression
1518 * @string: the string to scan for matches
1519 * @compile_options: compile options for the regular expression, or 0
1520 * @match_options: match options, or 0
1522 * Scans for a match in @string for @pattern.
1524 * This function is equivalent to g_regex_match() but it does not
1525 * require to compile the pattern with g_regex_new(), avoiding some
1526 * lines of code when you need just to do a match without extracting
1527 * substrings, capture counts, and so on.
1529 * If this function is to be called on the same @pattern more than
1530 * once, it's more efficient to compile the pattern once with
1531 * g_regex_new() and then use g_regex_match().
1533 * Returns: %TRUE if the string matched, %FALSE otherwise
1538 g_regex_match_simple (const gchar *pattern,
1539 const gchar *string,
1540 GRegexCompileFlags compile_options,
1541 GRegexMatchFlags match_options)
1546 regex = g_regex_new (pattern, compile_options, 0, NULL);
1549 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1550 g_regex_unref (regex);
1556 * @regex: a #GRegex structure from g_regex_new()
1557 * @string: the string to scan for matches
1558 * @match_options: match options
1559 * @match_info: (out) (allow-none): pointer to location where to store
1560 * the #GMatchInfo, or %NULL if you do not need it
1562 * Scans for a match in string for the pattern in @regex.
1563 * The @match_options are combined with the match options specified
1564 * when the @regex structure was created, letting you have more
1565 * flexibility in reusing #GRegex structures.
1567 * A #GMatchInfo structure, used to get information on the match,
1568 * is stored in @match_info if not %NULL. Note that if @match_info
1569 * is not %NULL then it is created even if the function returns %FALSE,
1570 * i.e. you must free it regardless if regular expression actually matched.
1572 * To retrieve all the non-overlapping matches of the pattern in
1573 * string you can use g_match_info_next().
1577 * print_uppercase_words (const gchar *string)
1579 * /* Print all uppercase-only words. */
1581 * GMatchInfo *match_info;
1583 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1584 * g_regex_match (regex, string, 0, &match_info);
1585 * while (g_match_info_matches (match_info))
1587 * gchar *word = g_match_info_fetch (match_info, 0);
1588 * g_print ("Found: %s\n", word);
1590 * g_match_info_next (match_info, NULL);
1592 * g_match_info_free (match_info);
1593 * g_regex_unref (regex);
1597 * @string is not copied and is used in #GMatchInfo internally. If
1598 * you use any #GMatchInfo method (except g_match_info_free()) after
1599 * freeing or modifying @string then the behaviour is undefined.
1601 * Returns: %TRUE is the string matched, %FALSE otherwise
1606 g_regex_match (const GRegex *regex,
1607 const gchar *string,
1608 GRegexMatchFlags match_options,
1609 GMatchInfo **match_info)
1611 return g_regex_match_full (regex, string, -1, 0, match_options,
1616 * g_regex_match_full:
1617 * @regex: a #GRegex structure from g_regex_new()
1618 * @string: (array length=string_len): the string to scan for matches
1619 * @string_len: the length of @string, or -1 if @string is nul-terminated
1620 * @start_position: starting index of the string to match
1621 * @match_options: match options
1622 * @match_info: (out) (allow-none): pointer to location where to store
1623 * the #GMatchInfo, or %NULL if you do not need it
1624 * @error: location to store the error occurring, or %NULL to ignore errors
1626 * Scans for a match in string for the pattern in @regex.
1627 * The @match_options are combined with the match options specified
1628 * when the @regex structure was created, letting you have more
1629 * flexibility in reusing #GRegex structures.
1631 * Setting @start_position differs from just passing over a shortened
1632 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1633 * that begins with any kind of lookbehind assertion, such as "\b".
1635 * A #GMatchInfo structure, used to get information on the match, is
1636 * stored in @match_info if not %NULL. Note that if @match_info is
1637 * not %NULL then it is created even if the function returns %FALSE,
1638 * i.e. you must free it regardless if regular expression actually
1641 * @string is not copied and is used in #GMatchInfo internally. If
1642 * you use any #GMatchInfo method (except g_match_info_free()) after
1643 * freeing or modifying @string then the behaviour is undefined.
1645 * To retrieve all the non-overlapping matches of the pattern in
1646 * string you can use g_match_info_next().
1650 * print_uppercase_words (const gchar *string)
1652 * /* Print all uppercase-only words. */
1654 * GMatchInfo *match_info;
1655 * GError *error = NULL;
1657 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1658 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1659 * while (g_match_info_matches (match_info))
1661 * gchar *word = g_match_info_fetch (match_info, 0);
1662 * g_print ("Found: %s\n", word);
1664 * g_match_info_next (match_info, &error);
1666 * g_match_info_free (match_info);
1667 * g_regex_unref (regex);
1668 * if (error != NULL)
1670 * g_printerr ("Error while matching: %s\n", error->message);
1671 * g_error_free (error);
1676 * Returns: %TRUE is the string matched, %FALSE otherwise
1681 g_regex_match_full (const GRegex *regex,
1682 const gchar *string,
1684 gint start_position,
1685 GRegexMatchFlags match_options,
1686 GMatchInfo **match_info,
1692 g_return_val_if_fail (regex != NULL, FALSE);
1693 g_return_val_if_fail (string != NULL, FALSE);
1694 g_return_val_if_fail (start_position >= 0, FALSE);
1695 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1696 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1698 info = match_info_new (regex, string, string_len, start_position,
1699 match_options, FALSE);
1700 match_ok = g_match_info_next (info, error);
1701 if (match_info != NULL)
1704 g_match_info_free (info);
1710 * g_regex_match_all:
1711 * @regex: a #GRegex structure from g_regex_new()
1712 * @string: the string to scan for matches
1713 * @match_options: match options
1714 * @match_info: (out) (allow-none): pointer to location where to store
1715 * the #GMatchInfo, or %NULL if you do not need it
1717 * Using the standard algorithm for regular expression matching only
1718 * the longest match in the string is retrieved. This function uses
1719 * a different algorithm so it can retrieve all the possible matches.
1720 * For more documentation see g_regex_match_all_full().
1722 * A #GMatchInfo structure, used to get information on the match, is
1723 * stored in @match_info if not %NULL. Note that if @match_info is
1724 * not %NULL then it is created even if the function returns %FALSE,
1725 * i.e. you must free it regardless if regular expression actually
1728 * @string is not copied and is used in #GMatchInfo internally. If
1729 * you use any #GMatchInfo method (except g_match_info_free()) after
1730 * freeing or modifying @string then the behaviour is undefined.
1732 * Returns: %TRUE is the string matched, %FALSE otherwise
1737 g_regex_match_all (const GRegex *regex,
1738 const gchar *string,
1739 GRegexMatchFlags match_options,
1740 GMatchInfo **match_info)
1742 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1747 * g_regex_match_all_full:
1748 * @regex: a #GRegex structure from g_regex_new()
1749 * @string: (array length=string_len): the string to scan for matches
1750 * @string_len: the length of @string, or -1 if @string is nul-terminated
1751 * @start_position: starting index of the string to match
1752 * @match_options: match options
1753 * @match_info: (out) (allow-none): pointer to location where to store
1754 * the #GMatchInfo, or %NULL if you do not need it
1755 * @error: location to store the error occurring, or %NULL to ignore errors
1757 * Using the standard algorithm for regular expression matching only
1758 * the longest match in the string is retrieved, it is not possible
1759 * to obtain all the available matches. For instance matching
1760 * "<a> <b> <c>" against the pattern "<.*>"
1761 * you get "<a> <b> <c>".
1763 * This function uses a different algorithm (called DFA, i.e. deterministic
1764 * finite automaton), so it can retrieve all the possible matches, all
1765 * starting at the same point in the string. For instance matching
1766 * "<a> <b> <c>" against the pattern "<.*>"
1767 * you would obtain three matches: "<a> <b> <c>",
1768 * "<a> <b>" and "<a>".
1770 * The number of matched strings is retrieved using
1771 * g_match_info_get_match_count(). To obtain the matched strings and
1772 * their position you can use, respectively, g_match_info_fetch() and
1773 * g_match_info_fetch_pos(). Note that the strings are returned in
1774 * reverse order of length; that is, the longest matching string is
1777 * Note that the DFA algorithm is slower than the standard one and it
1778 * is not able to capture substrings, so backreferences do not work.
1780 * Setting @start_position differs from just passing over a shortened
1781 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1782 * that begins with any kind of lookbehind assertion, such as "\b".
1784 * A #GMatchInfo structure, used to get information on the match, is
1785 * stored in @match_info if not %NULL. Note that if @match_info is
1786 * not %NULL then it is created even if the function returns %FALSE,
1787 * i.e. you must free it regardless if regular expression actually
1790 * @string is not copied and is used in #GMatchInfo internally. If
1791 * you use any #GMatchInfo method (except g_match_info_free()) after
1792 * freeing or modifying @string then the behaviour is undefined.
1794 * Returns: %TRUE is the string matched, %FALSE otherwise
1799 g_regex_match_all_full (const GRegex *regex,
1800 const gchar *string,
1802 gint start_position,
1803 GRegexMatchFlags match_options,
1804 GMatchInfo **match_info,
1810 g_return_val_if_fail (regex != NULL, FALSE);
1811 g_return_val_if_fail (string != NULL, FALSE);
1812 g_return_val_if_fail (start_position >= 0, FALSE);
1813 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1814 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1816 info = match_info_new (regex, string, string_len, start_position,
1817 match_options, TRUE);
1823 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1824 info->string, info->string_len,
1826 regex->match_opts | match_options,
1827 info->offsets, info->n_offsets,
1828 info->workspace, info->n_workspace);
1829 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1831 /* info->workspace is too small. */
1832 info->n_workspace *= 2;
1833 info->workspace = g_realloc (info->workspace,
1834 info->n_workspace * sizeof (gint));
1837 else if (info->matches == 0)
1839 /* info->offsets is too small. */
1840 info->n_offsets *= 2;
1841 info->offsets = g_realloc (info->offsets,
1842 info->n_offsets * sizeof (gint));
1845 else if (IS_PCRE_ERROR (info->matches))
1847 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1848 _("Error while matching regular expression %s: %s"),
1849 regex->pattern, match_error (info->matches));
1853 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1856 if (match_info != NULL)
1859 g_match_info_free (info);
1861 return info->matches >= 0;
1865 * g_regex_get_string_number:
1866 * @regex: #GRegex structure
1867 * @name: name of the subexpression
1869 * Retrieves the number of the subexpression named @name.
1871 * Returns: The number of the subexpression or -1 if @name
1877 g_regex_get_string_number (const GRegex *regex,
1882 g_return_val_if_fail (regex != NULL, -1);
1883 g_return_val_if_fail (name != NULL, -1);
1885 num = pcre_get_stringnumber (regex->pcre_re, name);
1886 if (num == PCRE_ERROR_NOSUBSTRING)
1893 * g_regex_split_simple:
1894 * @pattern: the regular expression
1895 * @string: the string to scan for matches
1896 * @compile_options: compile options for the regular expression, or 0
1897 * @match_options: match options, or 0
1899 * Breaks the string on the pattern, and returns an array of
1900 * the tokens. If the pattern contains capturing parentheses,
1901 * then the text for each of the substrings will also be returned.
1902 * If the pattern does not match anywhere in the string, then the
1903 * whole string is returned as the first token.
1905 * This function is equivalent to g_regex_split() but it does
1906 * not require to compile the pattern with g_regex_new(), avoiding
1907 * some lines of code when you need just to do a split without
1908 * extracting substrings, capture counts, and so on.
1910 * If this function is to be called on the same @pattern more than
1911 * once, it's more efficient to compile the pattern once with
1912 * g_regex_new() and then use g_regex_split().
1914 * As a special case, the result of splitting the empty string ""
1915 * is an empty vector, not a vector containing a single string.
1916 * The reason for this special case is that being able to represent
1917 * a empty vector is typically more useful than consistent handling
1918 * of empty elements. If you do need to represent empty elements,
1919 * you'll need to check for the empty string before calling this
1922 * A pattern that can match empty strings splits @string into
1923 * separate characters wherever it matches the empty string between
1924 * characters. For example splitting "ab c" using as a separator
1925 * "\s*", you will get "a", "b" and "c".
1927 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1932 g_regex_split_simple (const gchar *pattern,
1933 const gchar *string,
1934 GRegexCompileFlags compile_options,
1935 GRegexMatchFlags match_options)
1940 regex = g_regex_new (pattern, compile_options, 0, NULL);
1944 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1945 g_regex_unref (regex);
1951 * @regex: a #GRegex structure
1952 * @string: the string to split with the pattern
1953 * @match_options: match time option flags
1955 * Breaks the string on the pattern, and returns an array of the tokens.
1956 * If the pattern contains capturing parentheses, then the text for each
1957 * of the substrings will also be returned. If the pattern does not match
1958 * anywhere in the string, then the whole string is returned as the first
1961 * As a special case, the result of splitting the empty string "" is an
1962 * empty vector, not a vector containing a single string. The reason for
1963 * this special case is that being able to represent a empty vector is
1964 * typically more useful than consistent handling of empty elements. If
1965 * you do need to represent empty elements, you'll need to check for the
1966 * empty string before calling this function.
1968 * A pattern that can match empty strings splits @string into separate
1969 * characters wherever it matches the empty string between characters.
1970 * For example splitting "ab c" using as a separator "\s*", you will get
1973 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1978 g_regex_split (const GRegex *regex,
1979 const gchar *string,
1980 GRegexMatchFlags match_options)
1982 return g_regex_split_full (regex, string, -1, 0,
1983 match_options, 0, NULL);
1987 * g_regex_split_full:
1988 * @regex: a #GRegex structure
1989 * @string: (array length=string_len): the string to split with the pattern
1990 * @string_len: the length of @string, or -1 if @string is nul-terminated
1991 * @start_position: starting index of the string to match
1992 * @match_options: match time option flags
1993 * @max_tokens: the maximum number of tokens to split @string into.
1994 * If this is less than 1, the string is split completely
1995 * @error: return location for a #GError
1997 * Breaks the string on the pattern, and returns an array of the tokens.
1998 * If the pattern contains capturing parentheses, then the text for each
1999 * of the substrings will also be returned. If the pattern does not match
2000 * anywhere in the string, then the whole string is returned as the first
2003 * As a special case, the result of splitting the empty string "" is an
2004 * empty vector, not a vector containing a single string. The reason for
2005 * this special case is that being able to represent a empty vector is
2006 * typically more useful than consistent handling of empty elements. If
2007 * you do need to represent empty elements, you'll need to check for the
2008 * empty string before calling this function.
2010 * A pattern that can match empty strings splits @string into separate
2011 * characters wherever it matches the empty string between characters.
2012 * For example splitting "ab c" using as a separator "\s*", you will get
2015 * Setting @start_position differs from just passing over a shortened
2016 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2017 * that begins with any kind of lookbehind assertion, such as "\b".
2019 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
2024 g_regex_split_full (const GRegex *regex,
2025 const gchar *string,
2027 gint start_position,
2028 GRegexMatchFlags match_options,
2032 GError *tmp_error = NULL;
2033 GMatchInfo *match_info;
2038 /* position of the last separator. */
2039 gint last_separator_end;
2040 /* was the last match 0 bytes long? */
2041 gboolean last_match_is_empty;
2042 /* the returned array of char **s */
2043 gchar **string_list;
2045 g_return_val_if_fail (regex != NULL, NULL);
2046 g_return_val_if_fail (string != NULL, NULL);
2047 g_return_val_if_fail (start_position >= 0, NULL);
2048 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2049 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2051 if (max_tokens <= 0)
2052 max_tokens = G_MAXINT;
2055 string_len = strlen (string);
2057 /* zero-length string */
2058 if (string_len - start_position == 0)
2059 return g_new0 (gchar *, 1);
2061 if (max_tokens == 1)
2063 string_list = g_new0 (gchar *, 2);
2064 string_list[0] = g_strndup (&string[start_position],
2065 string_len - start_position);
2071 last_separator_end = start_position;
2072 last_match_is_empty = FALSE;
2074 match_ok = g_regex_match_full (regex, string, string_len, start_position,
2075 match_options, &match_info, &tmp_error);
2077 while (tmp_error == NULL)
2081 last_match_is_empty =
2082 (match_info->offsets[0] == match_info->offsets[1]);
2084 /* we need to skip empty separators at the same position of the end
2085 * of another separator. e.g. the string is "a b" and the separator
2086 * is " *", so from 1 to 2 we have a match and at position 2 we have
2087 * an empty match. */
2088 if (last_separator_end != match_info->offsets[1])
2093 token = g_strndup (string + last_separator_end,
2094 match_info->offsets[0] - last_separator_end);
2095 list = g_list_prepend (list, token);
2098 /* if there were substrings, these need to be added to
2100 match_count = g_match_info_get_match_count (match_info);
2101 if (match_count > 1)
2103 for (i = 1; i < match_count; i++)
2104 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
2110 /* if there was no match, copy to end of string. */
2111 if (!last_match_is_empty)
2113 gchar *token = g_strndup (string + last_separator_end,
2114 match_info->string_len - last_separator_end);
2115 list = g_list_prepend (list, token);
2117 /* no more tokens, end the loop. */
2121 /* -1 to leave room for the last part. */
2122 if (token_count >= max_tokens - 1)
2124 /* we have reached the maximum number of tokens, so we copy
2125 * the remaining part of the string. */
2126 if (last_match_is_empty)
2128 /* the last match was empty, so we have moved one char
2129 * after the real position to avoid empty matches at the
2131 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
2133 /* the if is needed in the case we have terminated the available
2134 * tokens, but we are at the end of the string, so there are no
2135 * characters left to copy. */
2136 if (string_len > match_info->pos)
2138 gchar *token = g_strndup (string + match_info->pos,
2139 string_len - match_info->pos);
2140 list = g_list_prepend (list, token);
2146 last_separator_end = match_info->pos;
2147 if (last_match_is_empty)
2148 /* if the last match was empty, g_match_info_next() has moved
2149 * forward to avoid infinite loops, but we still need to copy that
2151 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
2153 match_ok = g_match_info_next (match_info, &tmp_error);
2155 g_match_info_free (match_info);
2156 if (tmp_error != NULL)
2158 g_propagate_error (error, tmp_error);
2159 g_list_free_full (list, g_free);
2160 match_info->pos = -1;
2164 string_list = g_new (gchar *, g_list_length (list) + 1);
2166 for (last = g_list_last (list); last; last = g_list_previous (last))
2167 string_list[i++] = last->data;
2168 string_list[i] = NULL;
2177 REPL_TYPE_CHARACTER,
2178 REPL_TYPE_SYMBOLIC_REFERENCE,
2179 REPL_TYPE_NUMERIC_REFERENCE,
2180 REPL_TYPE_CHANGE_CASE
2185 CHANGE_CASE_NONE = 1 << 0,
2186 CHANGE_CASE_UPPER = 1 << 1,
2187 CHANGE_CASE_LOWER = 1 << 2,
2188 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
2189 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
2190 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
2191 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
2192 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
2195 struct _InterpolationData
2201 ChangeCase change_case;
2205 free_interpolation_data (InterpolationData *data)
2207 g_free (data->text);
2211 static const gchar *
2212 expand_escape (const gchar *replacement,
2214 InterpolationData *data,
2219 const gchar *error_detail;
2221 GError *tmp_error = NULL;
2229 data->type = REPL_TYPE_CHARACTER;
2234 data->type = REPL_TYPE_CHARACTER;
2239 data->type = REPL_TYPE_CHARACTER;
2244 data->type = REPL_TYPE_CHARACTER;
2249 data->type = REPL_TYPE_CHARACTER;
2254 data->type = REPL_TYPE_CHARACTER;
2259 data->type = REPL_TYPE_CHARACTER;
2264 data->type = REPL_TYPE_CHARACTER;
2274 h = g_ascii_xdigit_value (*p);
2277 error_detail = _("hexadecimal digit or '}' expected");
2288 for (i = 0; i < 2; i++)
2290 h = g_ascii_xdigit_value (*p);
2293 error_detail = _("hexadecimal digit expected");
2300 data->type = REPL_TYPE_STRING;
2301 data->text = g_new0 (gchar, 8);
2302 g_unichar_to_utf8 (x, data->text);
2306 data->type = REPL_TYPE_CHANGE_CASE;
2307 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2311 data->type = REPL_TYPE_CHANGE_CASE;
2312 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2316 data->type = REPL_TYPE_CHANGE_CASE;
2317 data->change_case = CHANGE_CASE_LOWER;
2321 data->type = REPL_TYPE_CHANGE_CASE;
2322 data->change_case = CHANGE_CASE_UPPER;
2326 data->type = REPL_TYPE_CHANGE_CASE;
2327 data->change_case = CHANGE_CASE_NONE;
2333 error_detail = _("missing '<' in symbolic reference");
2342 error_detail = _("unfinished symbolic reference");
2349 error_detail = _("zero-length symbolic reference");
2352 if (g_ascii_isdigit (*q))
2357 h = g_ascii_digit_value (*q);
2360 error_detail = _("digit expected");
2369 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2376 if (!g_ascii_isalnum (*r))
2378 error_detail = _("illegal symbolic reference");
2385 data->text = g_strndup (q, p - q);
2386 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2391 /* if \0 is followed by a number is an octal number representing a
2392 * character, else it is a numeric reference. */
2393 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2396 p = g_utf8_next_char (p);
2409 for (i = 0; i < 3; i++)
2411 h = g_ascii_digit_value (*p);
2421 if (i == 2 && base == 10)
2427 if (base == 8 || i == 3)
2429 data->type = REPL_TYPE_STRING;
2430 data->text = g_new0 (gchar, 8);
2431 g_unichar_to_utf8 (x, data->text);
2435 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2440 error_detail = _("stray final '\\'");
2444 error_detail = _("unknown escape sequence");
2451 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2452 tmp_error = g_error_new (G_REGEX_ERROR,
2453 G_REGEX_ERROR_REPLACE,
2454 _("Error while parsing replacement "
2455 "text \"%s\" at char %lu: %s"),
2457 (gulong)(p - replacement),
2459 g_propagate_error (error, tmp_error);
2465 split_replacement (const gchar *replacement,
2469 InterpolationData *data;
2470 const gchar *p, *start;
2472 start = p = replacement;
2477 data = g_new0 (InterpolationData, 1);
2478 start = p = expand_escape (replacement, p, data, error);
2481 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2482 free_interpolation_data (data);
2486 list = g_list_prepend (list, data);
2491 if (*p == '\\' || *p == '\0')
2495 data = g_new0 (InterpolationData, 1);
2496 data->text = g_strndup (start, p - start);
2497 data->type = REPL_TYPE_STRING;
2498 list = g_list_prepend (list, data);
2504 return g_list_reverse (list);
2507 /* Change the case of c based on change_case. */
2508 #define CHANGE_CASE(c, change_case) \
2509 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2510 g_unichar_tolower (c) : \
2511 g_unichar_toupper (c))
2514 string_append (GString *string,
2516 ChangeCase *change_case)
2520 if (text[0] == '\0')
2523 if (*change_case == CHANGE_CASE_NONE)
2525 g_string_append (string, text);
2527 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2529 c = g_utf8_get_char (text);
2530 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2531 g_string_append (string, g_utf8_next_char (text));
2532 *change_case = CHANGE_CASE_NONE;
2536 while (*text != '\0')
2538 c = g_utf8_get_char (text);
2539 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2540 text = g_utf8_next_char (text);
2546 interpolate_replacement (const GMatchInfo *match_info,
2551 InterpolationData *idata;
2553 ChangeCase change_case = CHANGE_CASE_NONE;
2555 for (list = data; list; list = list->next)
2558 switch (idata->type)
2560 case REPL_TYPE_STRING:
2561 string_append (result, idata->text, &change_case);
2563 case REPL_TYPE_CHARACTER:
2564 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2565 if (change_case & CHANGE_CASE_SINGLE_MASK)
2566 change_case = CHANGE_CASE_NONE;
2568 case REPL_TYPE_NUMERIC_REFERENCE:
2569 match = g_match_info_fetch (match_info, idata->num);
2572 string_append (result, match, &change_case);
2576 case REPL_TYPE_SYMBOLIC_REFERENCE:
2577 match = g_match_info_fetch_named (match_info, idata->text);
2580 string_append (result, match, &change_case);
2584 case REPL_TYPE_CHANGE_CASE:
2585 change_case = idata->change_case;
2593 /* whether actual match_info is needed for replacement, i.e.
2594 * whether there are references
2597 interpolation_list_needs_match (GList *list)
2599 while (list != NULL)
2601 InterpolationData *data = list->data;
2603 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2604 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2617 * @regex: a #GRegex structure
2618 * @string: (array length=string_len): the string to perform matches against
2619 * @string_len: the length of @string, or -1 if @string is nul-terminated
2620 * @start_position: starting index of the string to match
2621 * @replacement: text to replace each match with
2622 * @match_options: options for the match
2623 * @error: location to store the error occurring, or %NULL to ignore errors
2625 * Replaces all occurrences of the pattern in @regex with the
2626 * replacement text. Backreferences of the form '\number' or
2627 * '\g<number>' in the replacement text are interpolated by the
2628 * number-th captured subexpression of the match, '\g<name>' refers
2629 * to the captured subexpression with the given name. '\0' refers to the
2630 * complete match, but '\0' followed by a number is the octal representation
2631 * of a character. To include a literal '\' in the replacement, write '\\'.
2632 * There are also escapes that changes the case of the following text:
2635 * <varlistentry><term>\l</term>
2637 * <para>Convert to lower case the next character</para>
2640 * <varlistentry><term>\u</term>
2642 * <para>Convert to upper case the next character</para>
2645 * <varlistentry><term>\L</term>
2647 * <para>Convert to lower case till \E</para>
2650 * <varlistentry><term>\U</term>
2652 * <para>Convert to upper case till \E</para>
2655 * <varlistentry><term>\E</term>
2657 * <para>End case modification</para>
2662 * If you do not need to use backreferences use g_regex_replace_literal().
2664 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2665 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2666 * you can use g_regex_replace_literal().
2668 * Setting @start_position differs from just passing over a shortened
2669 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2670 * begins with any kind of lookbehind assertion, such as "\b".
2672 * Returns: a newly allocated string containing the replacements
2677 g_regex_replace (const GRegex *regex,
2678 const gchar *string,
2680 gint start_position,
2681 const gchar *replacement,
2682 GRegexMatchFlags match_options,
2687 GError *tmp_error = NULL;
2689 g_return_val_if_fail (regex != NULL, NULL);
2690 g_return_val_if_fail (string != NULL, NULL);
2691 g_return_val_if_fail (start_position >= 0, NULL);
2692 g_return_val_if_fail (replacement != NULL, NULL);
2693 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2694 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2696 list = split_replacement (replacement, &tmp_error);
2697 if (tmp_error != NULL)
2699 g_propagate_error (error, tmp_error);
2703 result = g_regex_replace_eval (regex,
2704 string, string_len, start_position,
2706 interpolate_replacement,
2709 if (tmp_error != NULL)
2710 g_propagate_error (error, tmp_error);
2712 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2718 literal_replacement (const GMatchInfo *match_info,
2722 g_string_append (result, data);
2727 * g_regex_replace_literal:
2728 * @regex: a #GRegex structure
2729 * @string: (array length=string_len): the string to perform matches against
2730 * @string_len: the length of @string, or -1 if @string is nul-terminated
2731 * @start_position: starting index of the string to match
2732 * @replacement: text to replace each match with
2733 * @match_options: options for the match
2734 * @error: location to store the error occurring, or %NULL to ignore errors
2736 * Replaces all occurrences of the pattern in @regex with the
2737 * replacement text. @replacement is replaced literally, to
2738 * include backreferences use g_regex_replace().
2740 * Setting @start_position differs from just passing over a
2741 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2742 * case of a pattern that begins with any kind of lookbehind
2743 * assertion, such as "\b".
2745 * Returns: a newly allocated string containing the replacements
2750 g_regex_replace_literal (const GRegex *regex,
2751 const gchar *string,
2753 gint start_position,
2754 const gchar *replacement,
2755 GRegexMatchFlags match_options,
2758 g_return_val_if_fail (replacement != NULL, NULL);
2759 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2761 return g_regex_replace_eval (regex,
2762 string, string_len, start_position,
2764 literal_replacement,
2765 (gpointer)replacement,
2770 * g_regex_replace_eval:
2771 * @regex: a #GRegex structure from g_regex_new()
2772 * @string: (array length=string_len): string to perform matches against
2773 * @string_len: the length of @string, or -1 if @string is nul-terminated
2774 * @start_position: starting index of the string to match
2775 * @match_options: options for the match
2776 * @eval: a function to call for each match
2777 * @user_data: user data to pass to the function
2778 * @error: location to store the error occurring, or %NULL to ignore errors
2780 * Replaces occurrences of the pattern in regex with the output of
2781 * @eval for that occurrence.
2783 * Setting @start_position differs from just passing over a shortened
2784 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2785 * that begins with any kind of lookbehind assertion, such as "\b".
2787 * The following example uses g_regex_replace_eval() to replace multiple
2791 * eval_cb (const GMatchInfo *info,
2798 * match = g_match_info_fetch (info, 0);
2799 * r = g_hash_table_lookup ((GHashTable *)data, match);
2800 * g_string_append (res, r);
2812 * h = g_hash_table_new (g_str_hash, g_str_equal);
2814 * g_hash_table_insert (h, "1", "ONE");
2815 * g_hash_table_insert (h, "2", "TWO");
2816 * g_hash_table_insert (h, "3", "THREE");
2817 * g_hash_table_insert (h, "4", "FOUR");
2819 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2820 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2821 * g_hash_table_destroy (h);
2826 * Returns: a newly allocated string containing the replacements
2831 g_regex_replace_eval (const GRegex *regex,
2832 const gchar *string,
2834 gint start_position,
2835 GRegexMatchFlags match_options,
2836 GRegexEvalCallback eval,
2840 GMatchInfo *match_info;
2843 gboolean done = FALSE;
2844 GError *tmp_error = NULL;
2846 g_return_val_if_fail (regex != NULL, NULL);
2847 g_return_val_if_fail (string != NULL, NULL);
2848 g_return_val_if_fail (start_position >= 0, NULL);
2849 g_return_val_if_fail (eval != NULL, NULL);
2850 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2853 string_len = strlen (string);
2855 result = g_string_sized_new (string_len);
2857 /* run down the string making matches. */
2858 g_regex_match_full (regex, string, string_len, start_position,
2859 match_options, &match_info, &tmp_error);
2860 while (!done && g_match_info_matches (match_info))
2862 g_string_append_len (result,
2864 match_info->offsets[0] - str_pos);
2865 done = (*eval) (match_info, result, user_data);
2866 str_pos = match_info->offsets[1];
2867 g_match_info_next (match_info, &tmp_error);
2869 g_match_info_free (match_info);
2870 if (tmp_error != NULL)
2872 g_propagate_error (error, tmp_error);
2873 g_string_free (result, TRUE);
2877 g_string_append_len (result, string + str_pos, string_len - str_pos);
2878 return g_string_free (result, FALSE);
2882 * g_regex_check_replacement:
2883 * @replacement: the replacement string
2884 * @has_references: (out) (allow-none): location to store information about
2885 * references in @replacement or %NULL
2886 * @error: location to store error
2888 * Checks whether @replacement is a valid replacement string
2889 * (see g_regex_replace()), i.e. that all escape sequences in
2892 * If @has_references is not %NULL then @replacement is checked
2893 * for pattern references. For instance, replacement text 'foo\n'
2894 * does not contain references and may be evaluated without information
2895 * about actual match, but '\0\1' (whole match followed by first
2896 * subpattern) requires valid #GMatchInfo object.
2898 * Returns: whether @replacement is a valid replacement string
2903 g_regex_check_replacement (const gchar *replacement,
2904 gboolean *has_references,
2910 list = split_replacement (replacement, &tmp);
2914 g_propagate_error (error, tmp);
2919 *has_references = interpolation_list_needs_match (list);
2921 g_list_free_full (list, (GDestroyNotify) free_interpolation_data);
2927 * g_regex_escape_nul:
2928 * @string: the string to escape
2929 * @length: the length of @string
2931 * Escapes the nul characters in @string to "\x00". It can be used
2932 * to compile a regex with embedded nul characters.
2934 * For completeness, @length can be -1 for a nul-terminated string.
2935 * In this case the output string will be of course equal to @string.
2937 * Returns: a newly-allocated escaped string
2942 g_regex_escape_nul (const gchar *string,
2946 const gchar *p, *piece_start, *end;
2949 g_return_val_if_fail (string != NULL, NULL);
2952 return g_strdup (string);
2954 end = string + length;
2955 p = piece_start = string;
2956 escaped = g_string_sized_new (length + 1);
2964 if (p != piece_start)
2966 /* copy the previous piece. */
2967 g_string_append_len (escaped, piece_start, p - piece_start);
2969 if ((backslashes & 1) == 0)
2970 g_string_append_c (escaped, '\\');
2971 g_string_append_c (escaped, 'x');
2972 g_string_append_c (escaped, '0');
2973 g_string_append_c (escaped, '0');
2983 p = g_utf8_next_char (p);
2988 if (piece_start < end)
2989 g_string_append_len (escaped, piece_start, end - piece_start);
2991 return g_string_free (escaped, FALSE);
2995 * g_regex_escape_string:
2996 * @string: (array length=length): the string to escape
2997 * @length: the length of @string, or -1 if @string is nul-terminated
2999 * Escapes the special characters used for regular expressions
3000 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
3001 * function is useful to dynamically generate regular expressions.
3003 * @string can contain nul characters that are replaced with "\0",
3004 * in this case remember to specify the correct length of @string
3007 * Returns: a newly-allocated escaped string
3012 g_regex_escape_string (const gchar *string,
3016 const char *p, *piece_start, *end;
3018 g_return_val_if_fail (string != NULL, NULL);
3021 length = strlen (string);
3023 end = string + length;
3024 p = piece_start = string;
3025 escaped = g_string_sized_new (length + 1);
3046 if (p != piece_start)
3047 /* copy the previous piece. */
3048 g_string_append_len (escaped, piece_start, p - piece_start);
3049 g_string_append_c (escaped, '\\');
3051 g_string_append_c (escaped, '0');
3053 g_string_append_c (escaped, *p);
3057 p = g_utf8_next_char (p);
3062 if (piece_start < end)
3063 g_string_append_len (escaped, piece_start, end - piece_start);
3065 return g_string_free (escaped, FALSE);