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
30 #ifdef USE_SYSTEM_PCRE
33 #include "pcre/pcre.h"
37 /* Mask of all the possible values for GRegexCompileFlags. */
38 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
43 G_REGEX_DOLLAR_ENDONLY | \
46 G_REGEX_NO_AUTO_CAPTURE | \
49 G_REGEX_NEWLINE_CR | \
50 G_REGEX_NEWLINE_LF | \
53 /* Mask of all the possible values for GRegexMatchFlags. */
54 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
55 G_REGEX_MATCH_NOTBOL | \
56 G_REGEX_MATCH_NOTEOL | \
57 G_REGEX_MATCH_NOTEMPTY | \
58 G_REGEX_MATCH_PARTIAL | \
59 G_REGEX_MATCH_NEWLINE_CR | \
60 G_REGEX_MATCH_NEWLINE_LF | \
61 G_REGEX_MATCH_NEWLINE_CRLF | \
62 G_REGEX_MATCH_NEWLINE_ANY)
64 /* if the string is in UTF-8 use g_utf8_ functions, else use
66 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
67 g_utf8_next_char (s) : \
69 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
70 g_utf8_prev_char (s) : \
75 GRegex *regex; /* the regex */
76 GRegexMatchFlags match_opts; /* options used at match time on the regex */
77 gint matches; /* number of matching sub patterns */
78 gint pos; /* position in the string where last match left off */
79 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
80 gint n_offsets; /* number of offsets */
81 gint *workspace; /* workspace for pcre_dfa_exec() */
82 gint n_workspace; /* number of workspace elements */
83 const gchar *string; /* string passed to the match function */
84 gssize string_len; /* length of string */
89 volatile gint ref_count; /* the ref count for the immutable part */
90 gchar *pattern; /* the pattern */
91 pcre *pcre_re; /* compiled form of the pattern */
92 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
93 GRegexMatchFlags match_opts; /* options used at match time on the regex */
94 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
97 /* TRUE if ret is an error code, FALSE otherwise. */
98 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
100 typedef struct _InterpolationData InterpolationData;
101 static gboolean interpolation_list_needs_match (GList *list);
102 static gboolean interpolate_replacement (const GMatchInfo *match_info,
105 static GList *split_replacement (const gchar *replacement,
107 static void free_interpolation_data (InterpolationData *data);
111 match_error (gint errcode)
115 case PCRE_ERROR_NOMATCH:
118 case PCRE_ERROR_NULL:
119 /* NULL argument, this should not happen in GRegex */
120 g_warning ("A NULL argument was passed to PCRE");
122 case PCRE_ERROR_BADOPTION:
123 return "bad options";
124 case PCRE_ERROR_BADMAGIC:
125 return _("corrupted object");
126 case PCRE_ERROR_UNKNOWN_OPCODE:
127 return N_("internal error or corrupted object");
128 case PCRE_ERROR_NOMEMORY:
129 return _("out of memory");
130 case PCRE_ERROR_NOSUBSTRING:
131 /* not used by pcre_exec() */
133 case PCRE_ERROR_MATCHLIMIT:
134 return _("backtracking limit reached");
135 case PCRE_ERROR_CALLOUT:
136 /* callouts are not implemented */
138 case PCRE_ERROR_BADUTF8:
139 case PCRE_ERROR_BADUTF8_OFFSET:
140 /* we do not check if strings are valid */
142 case PCRE_ERROR_PARTIAL:
145 case PCRE_ERROR_BADPARTIAL:
146 return _("the pattern contains items not supported for partial matching");
147 case PCRE_ERROR_INTERNAL:
148 return _("internal error");
149 case PCRE_ERROR_BADCOUNT:
150 /* negative ovecsize, this should not happen in GRegex */
151 g_warning ("A negative ovecsize was passed to PCRE");
153 case PCRE_ERROR_DFA_UITEM:
154 return _("the pattern contains items not supported for partial matching");
155 case PCRE_ERROR_DFA_UCOND:
156 return _("back references as conditions are not supported for partial matching");
157 case PCRE_ERROR_DFA_UMLIMIT:
158 /* the match_field field is not used in GRegex */
160 case PCRE_ERROR_DFA_WSSIZE:
161 /* handled expanding the workspace */
163 case PCRE_ERROR_DFA_RECURSE:
164 case PCRE_ERROR_RECURSIONLIMIT:
165 return _("recursion limit reached");
166 case PCRE_ERROR_NULLWSLIMIT:
167 return _("workspace limit for empty substrings reached");
168 case PCRE_ERROR_BADNEWLINE:
169 return _("invalid combination of newline flags");
173 return _("unknown error");
177 translate_compile_error (gint *errcode, const gchar **errmsg)
179 /* Compile errors are created adding 100 to the error code returned
181 * If errcode is known we put the translatable error message in
182 * erromsg. If errcode is unknown we put the generic
183 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
184 * untranslated error message returned by PCRE.
185 * Note that there can be more PCRE errors with the same GRegexError
186 * and that some PCRE errors are useless for us.
192 case G_REGEX_ERROR_STRAY_BACKSLASH:
193 *errmsg = _("\\ at end of pattern");
195 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
196 *errmsg = _("\\c at end of pattern");
198 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
199 *errmsg = _("unrecognized character follows \\");
202 /* A number of Perl escapes are not handled by PCRE.
203 * Therefore it explicitly raises ERR37.
205 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
206 *errmsg = _("case-changing escapes (\\l, \\L, \\u, \\U) are not allowed here");
208 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
209 *errmsg = _("numbers out of order in {} quantifier");
211 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
212 *errmsg = _("number too big in {} quantifier");
214 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
215 *errmsg = _("missing terminating ] for character class");
217 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
218 *errmsg = _("invalid escape sequence in character class");
220 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
221 *errmsg = _("range out of order in character class");
223 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
224 *errmsg = _("nothing to repeat");
226 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
227 *errmsg = _("unrecognized character after (?");
230 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
231 *errmsg = _("unrecognized character after (?<");
234 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
235 *errmsg = _("unrecognized character after (?P");
237 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
238 *errmsg = _("POSIX named classes are supported only within a class");
240 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
241 *errmsg = _("missing terminating )");
244 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
245 *errmsg = _(") without opening (");
248 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
249 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
250 * sequences here, '(?-54' would be an example for the second group.
252 *errmsg = _("(?R or (?[+-]digits must be followed by )");
254 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
255 *errmsg = _("reference to non-existent subpattern");
257 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
258 *errmsg = _("missing ) after comment");
260 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
261 *errmsg = _("regular expression too large");
263 case G_REGEX_ERROR_MEMORY_ERROR:
264 *errmsg = _("failed to get memory");
266 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
267 *errmsg = _("lookbehind assertion is not fixed length");
269 case G_REGEX_ERROR_MALFORMED_CONDITION:
270 *errmsg = _("malformed number or name after (?(");
272 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
273 *errmsg = _("conditional group contains more than two branches");
275 case G_REGEX_ERROR_ASSERTION_EXPECTED:
276 *errmsg = _("assertion expected after (?(");
278 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
279 *errmsg = _("unknown POSIX class name");
281 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
282 *errmsg = _("POSIX collating elements are not supported");
284 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
285 *errmsg = _("character value in \\x{...} sequence is too large");
287 case G_REGEX_ERROR_INVALID_CONDITION:
288 *errmsg = _("invalid condition (?(0)");
290 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
291 *errmsg = _("\\C not allowed in lookbehind assertion");
293 case G_REGEX_ERROR_INFINITE_LOOP:
294 *errmsg = _("recursive call could loop indefinitely");
296 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
297 *errmsg = _("missing terminator in subpattern name");
299 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
300 *errmsg = _("two named subpatterns have the same name");
302 case G_REGEX_ERROR_MALFORMED_PROPERTY:
303 *errmsg = _("malformed \\P or \\p sequence");
305 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
306 *errmsg = _("unknown property name after \\P or \\p");
308 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
309 *errmsg = _("subpattern name is too long (maximum 32 characters)");
311 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
312 *errmsg = _("too many named subpatterns (maximum 10,000)");
314 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
315 *errmsg = _("octal value is greater than \\377");
317 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
318 *errmsg = _("DEFINE group contains more than one branch");
320 case G_REGEX_ERROR_DEFINE_REPETION:
321 *errmsg = _("repeating a DEFINE group is not allowed");
323 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
324 *errmsg = _("inconsistent NEWLINE options");
326 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
327 *errmsg = _("\\g is not followed by a braced name or an optionally "
328 "braced non-zero number");
331 *errcode = G_REGEX_ERROR_INTERNAL;
332 *errmsg = _("unexpected repeat");
335 *errcode = G_REGEX_ERROR_INTERNAL;
336 *errmsg = _("code overflow");
339 *errcode = G_REGEX_ERROR_INTERNAL;
340 *errmsg = _("overran compiling workspace");
343 *errcode = G_REGEX_ERROR_INTERNAL;
344 *errmsg = _("previously-checked referenced subpattern not found");
347 /* This should not happen as we never pass a NULL erroffset */
348 g_warning ("erroffset passed as NULL");
349 *errcode = G_REGEX_ERROR_COMPILE;
352 /* This should not happen as we check options before passing them
353 * to pcre_compile2() */
354 g_warning ("unknown option bit(s) set");
355 *errcode = G_REGEX_ERROR_COMPILE;
360 /* These errors should not happen as we are using an UTF8-enabled PCRE
361 * and we do not check if strings are valid */
362 g_warning ("%s", *errmsg);
363 *errcode = G_REGEX_ERROR_COMPILE;
366 *errcode = G_REGEX_ERROR_COMPILE;
373 match_info_new (const GRegex *regex,
380 GMatchInfo *match_info;
383 string_len = strlen (string);
385 match_info = g_new0 (GMatchInfo, 1);
386 match_info->regex = g_regex_ref ((GRegex *)regex);
387 match_info->string = string;
388 match_info->string_len = string_len;
389 match_info->matches = PCRE_ERROR_NOMATCH;
390 match_info->pos = start_position;
391 match_info->match_opts = match_options;
395 /* These values should be enough for most cases, if they are not
396 * enough g_regex_match_all_full() will expand them. */
397 match_info->n_offsets = 24;
398 match_info->n_workspace = 100;
399 match_info->workspace = g_new (gint, match_info->n_workspace);
404 pcre_fullinfo (regex->pcre_re, regex->extra,
405 PCRE_INFO_CAPTURECOUNT, &capture_count);
406 match_info->n_offsets = (capture_count + 1) * 3;
409 match_info->offsets = g_new0 (gint, match_info->n_offsets);
410 /* Set an invalid position for the previous match. */
411 match_info->offsets[0] = -1;
412 match_info->offsets[1] = -1;
418 * g_match_info_get_regex:
419 * @match_info: a #GMatchInfo
421 * Returns #GRegex object used in @match_info. It belongs to Glib
422 * and must not be freed. Use g_regex_ref() if you need to keep it
423 * after you free @match_info object.
425 * Returns: #GRegex object used in @match_info
430 g_match_info_get_regex (const GMatchInfo *match_info)
432 g_return_val_if_fail (match_info != NULL, NULL);
433 return match_info->regex;
437 * g_match_info_get_string:
438 * @match_info: a #GMatchInfo
440 * Returns the string searched with @match_info. This is the
441 * string passed to g_regex_match() or g_regex_replace() so
442 * you may not free it before calling this function.
444 * Returns: the string searched with @match_info
449 g_match_info_get_string (const GMatchInfo *match_info)
451 g_return_val_if_fail (match_info != NULL, NULL);
452 return match_info->string;
457 * @match_info: a #GMatchInfo
459 * Frees all the memory associated with the #GMatchInfo structure.
464 g_match_info_free (GMatchInfo *match_info)
468 g_regex_unref (match_info->regex);
469 g_free (match_info->offsets);
470 g_free (match_info->workspace);
477 * @match_info: a #GMatchInfo structure
478 * @error: location to store the error occuring, or %NULL to ignore errors
480 * Scans for the next match using the same parameters of the previous
481 * call to g_regex_match_full() or g_regex_match() that returned
484 * The match is done on the string passed to the match function, so you
485 * cannot free it before calling this function.
487 * Returns: %TRUE is the string matched, %FALSE otherwise
492 g_match_info_next (GMatchInfo *match_info,
495 gint prev_match_start;
498 g_return_val_if_fail (match_info != NULL, FALSE);
499 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
500 g_return_val_if_fail (match_info->pos >= 0, FALSE);
502 prev_match_start = match_info->offsets[0];
503 prev_match_end = match_info->offsets[1];
505 match_info->matches = pcre_exec (match_info->regex->pcre_re,
506 match_info->regex->extra,
508 match_info->string_len,
510 match_info->regex->match_opts | match_info->match_opts,
512 match_info->n_offsets);
513 if (IS_PCRE_ERROR (match_info->matches))
515 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
516 _("Error while matching regular expression %s: %s"),
517 match_info->regex->pattern, match_error (match_info->matches));
521 /* avoid infinite loops if the pattern is an empty string or something
523 if (match_info->pos == match_info->offsets[1])
525 if (match_info->pos > match_info->string_len)
527 /* we have reached the end of the string */
528 match_info->pos = -1;
529 match_info->matches = PCRE_ERROR_NOMATCH;
533 match_info->pos = NEXT_CHAR (match_info->regex,
534 &match_info->string[match_info->pos]) -
539 match_info->pos = match_info->offsets[1];
542 /* it's possible to get two identical matches when we are matching
543 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
544 * the string is "RegExTest" we have:
545 * - search at position 0: match from 0 to 0
546 * - search at position 1: match from 3 to 3
547 * - search at position 3: match from 3 to 3 (duplicate)
548 * - search at position 4: match from 5 to 5
549 * - search at position 5: match from 5 to 5 (duplicate)
550 * - search at position 6: no match -> stop
551 * so we have to ignore the duplicates.
552 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
553 if (match_info->matches >= 0 &&
554 prev_match_start == match_info->offsets[0] &&
555 prev_match_end == match_info->offsets[1])
557 /* ignore this match and search the next one */
558 return g_match_info_next (match_info, error);
561 return match_info->matches >= 0;
565 * g_match_info_matches:
566 * @match_info: a #GMatchInfo structure
568 * Returns whether the previous match operation succeeded.
570 * Returns: %TRUE if the previous match operation succeeded,
576 g_match_info_matches (const GMatchInfo *match_info)
578 g_return_val_if_fail (match_info != NULL, FALSE);
580 return match_info->matches >= 0;
584 * g_match_info_get_match_count:
585 * @match_info: a #GMatchInfo structure
587 * Retrieves the number of matched substrings (including substring 0,
588 * that is the whole matched text), so 1 is returned if the pattern
589 * has no substrings in it and 0 is returned if the match failed.
591 * If the last match was obtained using the DFA algorithm, that is
592 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
593 * count is not that of the number of capturing parentheses but that of
594 * the number of matched substrings.
596 * Returns: Number of matched substrings, or -1 if an error occurred
601 g_match_info_get_match_count (const GMatchInfo *match_info)
603 g_return_val_if_fail (match_info, -1);
605 if (match_info->matches == PCRE_ERROR_NOMATCH)
608 else if (match_info->matches < PCRE_ERROR_NOMATCH)
613 return match_info->matches;
617 * g_match_info_is_partial_match:
618 * @match_info: a #GMatchInfo structure
620 * Usually if the string passed to g_regex_match*() matches as far as
621 * it goes, but is too short to match the entire pattern, %FALSE is
622 * returned. There are circumstances where it might be helpful to
623 * distinguish this case from other cases in which there is no match.
625 * Consider, for example, an application where a human is required to
626 * type in data for a field with specific formatting requirements. An
627 * example might be a date in the form ddmmmyy, defined by the pattern
628 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
629 * If the application sees the user’s keystrokes one by one, and can
630 * check that what has been typed so far is potentially valid, it is
631 * able to raise an error as soon as a mistake is made.
633 * GRegex supports the concept of partial matching by means of the
634 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
635 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
636 * for a complete match, %FALSE otherwise. But, when these functions
637 * return %FALSE, you can check if the match was partial calling
638 * g_match_info_is_partial_match().
640 * When using partial matching you cannot use g_match_info_fetch*().
642 * Because of the way certain internal optimizations are implemented
643 * the partial matching algorithm cannot be used with all patterns.
644 * So repeated single characters such as "a{2,4}" and repeated single
645 * meta-sequences such as "\d+" are not permitted if the maximum number
646 * of occurrences is greater than one. Optional items such as "\d?"
647 * (where the maximum is one) are permitted. Quantifiers with any values
648 * are permitted after parentheses, so the invalid examples above can be
649 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
650 * for a pattern that does not conform to the restrictions, matching
651 * functions return an error.
653 * Returns: %TRUE if the match was partial, %FALSE otherwise
658 g_match_info_is_partial_match (const GMatchInfo *match_info)
660 g_return_val_if_fail (match_info != NULL, FALSE);
662 return match_info->matches == PCRE_ERROR_PARTIAL;
666 * g_match_info_expand_references:
667 * @match_info: a #GMatchInfo or %NULL
668 * @string_to_expand: the string to expand
669 * @error: location to store the error occuring, or %NULL to ignore errors
671 * Returns a new string containing the text in @string_to_expand with
672 * references and escape sequences expanded. References refer to the last
673 * match done with @string against @regex and have the same syntax used by
676 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
677 * passed to g_regex_new().
679 * The backreferences are extracted from the string passed to the match
680 * function, so you cannot call this function after freeing the string.
682 * @match_info may be %NULL in which case @string_to_expand must not
683 * contain references. For instance "foo\n" does not refer to an actual
684 * pattern and '\n' merely will be replaced with \n character,
685 * while to expand "\0" (whole match) one needs the result of a match.
686 * Use g_regex_check_replacement() to find out whether @string_to_expand
687 * contains references.
689 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
694 g_match_info_expand_references (const GMatchInfo *match_info,
695 const gchar *string_to_expand,
700 GError *tmp_error = NULL;
702 g_return_val_if_fail (string_to_expand != NULL, NULL);
703 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
705 list = split_replacement (string_to_expand, &tmp_error);
706 if (tmp_error != NULL)
708 g_propagate_error (error, tmp_error);
712 if (!match_info && interpolation_list_needs_match (list))
714 g_critical ("String '%s' contains references to the match, can't "
715 "expand references without GMatchInfo object",
720 result = g_string_sized_new (strlen (string_to_expand));
721 interpolate_replacement (match_info, result, list);
723 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
726 return g_string_free (result, FALSE);
730 * g_match_info_fetch:
731 * @match_info: #GMatchInfo structure
732 * @match_num: number of the sub expression
734 * Retrieves the text matching the @match_num<!-- -->'th capturing
735 * parentheses. 0 is the full text of the match, 1 is the first paren
736 * set, 2 the second, and so on.
738 * If @match_num is a valid sub pattern but it didn't match anything
739 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
740 * string is returned.
742 * If the match was obtained using the DFA algorithm, that is using
743 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
744 * string is not that of a set of parentheses but that of a matched
745 * substring. Substrings are matched in reverse order of length, so
746 * 0 is the longest match.
748 * The string is fetched from the string passed to the match function,
749 * so you cannot call this function after freeing the string.
751 * Returns: (allow-none): The matched substring, or %NULL if an error
752 * occurred. You have to free the string yourself
757 g_match_info_fetch (const GMatchInfo *match_info,
760 /* we cannot use pcre_get_substring() because it allocates the
761 * string using pcre_malloc(). */
765 g_return_val_if_fail (match_info != NULL, NULL);
766 g_return_val_if_fail (match_num >= 0, NULL);
768 /* match_num does not exist or it didn't matched, i.e. matching "b"
769 * against "(a)?b" then group 0 is empty. */
770 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
772 else if (start == -1)
773 match = g_strdup ("");
775 match = g_strndup (&match_info->string[start], end - start);
781 * g_match_info_fetch_pos:
782 * @match_info: #GMatchInfo structure
783 * @match_num: number of the sub expression
784 * @start_pos: (out) (allow-none): pointer to location where to store
785 * the start position, or %NULL
786 * @end_pos: (out) (allow-none): pointer to location where to store
787 * the end position, or %NULL
789 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
790 * parentheses. 0 is the full text of the match, 1 is the first
791 * paren set, 2 the second, and so on.
793 * If @match_num is a valid sub pattern but it didn't match anything
794 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
795 * and @end_pos are set to -1 and %TRUE is returned.
797 * If the match was obtained using the DFA algorithm, that is using
798 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
799 * position is not that of a set of parentheses but that of a matched
800 * substring. Substrings are matched in reverse order of length, so
801 * 0 is the longest match.
803 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
804 * the position cannot be fetched, @start_pos and @end_pos are left
810 g_match_info_fetch_pos (const GMatchInfo *match_info,
815 g_return_val_if_fail (match_info != NULL, FALSE);
816 g_return_val_if_fail (match_num >= 0, FALSE);
818 /* make sure the sub expression number they're requesting is less than
819 * the total number of sub expressions that were matched. */
820 if (match_num >= match_info->matches)
823 if (start_pos != NULL)
824 *start_pos = match_info->offsets[2 * match_num];
827 *end_pos = match_info->offsets[2 * match_num + 1];
833 * Returns number of first matched subpattern with name @name.
834 * There may be more than one in case when DUPNAMES is used,
835 * and not all subpatterns with that name match;
836 * pcre_get_stringnumber() does not work in that case.
839 get_matched_substring_number (const GMatchInfo *match_info,
846 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
847 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
849 /* This code is copied from pcre_get.c: get_first_set() */
850 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
858 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
860 gint n = (entry[0] << 8) + entry[1];
861 if (match_info->offsets[n*2] >= 0)
865 return (first[0] << 8) + first[1];
869 * g_match_info_fetch_named:
870 * @match_info: #GMatchInfo structure
871 * @name: name of the subexpression
873 * Retrieves the text matching the capturing parentheses named @name.
875 * If @name is a valid sub pattern name but it didn't match anything
876 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
877 * then an empty string is returned.
879 * The string is fetched from the string passed to the match function,
880 * so you cannot call this function after freeing the string.
882 * Returns: (allow-none): The matched substring, or %NULL if an error
883 * occurred. You have to free the string yourself
888 g_match_info_fetch_named (const GMatchInfo *match_info,
891 /* we cannot use pcre_get_named_substring() because it allocates the
892 * string using pcre_malloc(). */
895 g_return_val_if_fail (match_info != NULL, NULL);
896 g_return_val_if_fail (name != NULL, NULL);
898 num = get_matched_substring_number (match_info, name);
902 return g_match_info_fetch (match_info, num);
906 * g_match_info_fetch_named_pos:
907 * @match_info: #GMatchInfo structure
908 * @name: name of the subexpression
909 * @start_pos: (out) (allow-none): pointer to location where to store
910 * the start position, or %NULL
911 * @end_pos: (out) (allow-none): pointer to location where to store
912 * the end position, or %NULL
914 * Retrieves the position in bytes of the capturing parentheses named @name.
916 * If @name is a valid sub pattern name but it didn't match anything
917 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
918 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
920 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
921 * If the position cannot be fetched, @start_pos and @end_pos
922 * are left unchanged.
927 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
934 g_return_val_if_fail (match_info != NULL, FALSE);
935 g_return_val_if_fail (name != NULL, FALSE);
937 num = get_matched_substring_number (match_info, name);
941 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
945 * g_match_info_fetch_all:
946 * @match_info: a #GMatchInfo structure
948 * Bundles up pointers to each of the matching substrings from a match
949 * and stores them in an array of gchar pointers. The first element in
950 * the returned array is the match number 0, i.e. the entire matched
953 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
954 * "b" against "(a)?b") then an empty string is inserted.
956 * If the last match was obtained using the DFA algorithm, that is using
957 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
958 * strings are not that matched by sets of parentheses but that of the
959 * matched substring. Substrings are matched in reverse order of length,
960 * so the first one is the longest match.
962 * The strings are fetched from the string passed to the match function,
963 * so you cannot call this function after freeing the string.
965 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
966 * It must be freed using g_strfreev(). If the previous match failed
972 g_match_info_fetch_all (const GMatchInfo *match_info)
974 /* we cannot use pcre_get_substring_list() because the returned value
975 * isn't suitable for g_strfreev(). */
979 g_return_val_if_fail (match_info != NULL, NULL);
981 if (match_info->matches < 0)
984 result = g_new (gchar *, match_info->matches + 1);
985 for (i = 0; i < match_info->matches; i++)
986 result[i] = g_match_info_fetch (match_info, i);
996 g_regex_error_quark (void)
998 static GQuark error_quark = 0;
1000 if (error_quark == 0)
1001 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1010 * Increases reference count of @regex by 1.
1017 g_regex_ref (GRegex *regex)
1019 g_return_val_if_fail (regex != NULL, NULL);
1020 g_atomic_int_inc (®ex->ref_count);
1028 * Decreases reference count of @regex by 1. When reference count drops
1029 * to zero, it frees all the memory associated with the regex structure.
1034 g_regex_unref (GRegex *regex)
1036 g_return_if_fail (regex != NULL);
1038 if (g_atomic_int_exchange_and_add (®ex->ref_count, -1) - 1 == 0)
1040 g_free (regex->pattern);
1041 if (regex->pcre_re != NULL)
1042 pcre_free (regex->pcre_re);
1043 if (regex->extra != NULL)
1044 pcre_free (regex->extra);
1051 * @pattern: the regular expression
1052 * @compile_options: compile options for the regular expression, or 0
1053 * @match_options: match options for the regular expression, or 0
1054 * @error: return location for a #GError
1056 * Compiles the regular expression to an internal form, and does
1057 * the initial setup of the #GRegex structure.
1059 * Returns: a #GRegex structure. Call g_regex_unref() when you
1065 g_regex_new (const gchar *pattern,
1066 GRegexCompileFlags compile_options,
1067 GRegexMatchFlags match_options,
1072 const gchar *errmsg;
1075 gboolean optimize = FALSE;
1076 static gboolean initialized = FALSE;
1077 unsigned long int pcre_compile_options;
1079 g_return_val_if_fail (pattern != NULL, NULL);
1080 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1081 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1082 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1089 pcre_config (PCRE_CONFIG_UTF8, &support);
1092 msg = N_("PCRE library is compiled without UTF8 support");
1093 g_critical ("%s", msg);
1094 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1098 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
1101 msg = N_("PCRE library is compiled without UTF8 properties support");
1102 g_critical ("%s", msg);
1103 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1110 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1111 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1112 if (compile_options & G_REGEX_OPTIMIZE)
1115 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1116 * instead uses UTF-8 only if required with PCRE_UTF8. */
1117 if (compile_options & G_REGEX_RAW)
1120 compile_options &= ~G_REGEX_RAW;
1125 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1126 match_options |= PCRE_NO_UTF8_CHECK;
1129 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1130 * not for the system one. */
1131 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1132 !(compile_options & G_REGEX_NEWLINE_LF))
1134 compile_options |= PCRE_NEWLINE_ANY;
1137 /* compile the pattern */
1138 re = pcre_compile2 (pattern, compile_options, &errcode,
1139 &errmsg, &erroffset, NULL);
1141 /* if the compilation failed, set the error member and return
1147 /* Translate the PCRE error code to GRegexError and use a translated
1148 * error message if possible */
1149 translate_compile_error (&errcode, &errmsg);
1151 /* PCRE uses byte offsets but we want to show character offsets */
1152 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1154 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1155 _("Error while compiling regular "
1156 "expression %s at char %d: %s"),
1157 pattern, erroffset, errmsg);
1158 g_propagate_error (error, tmp_error);
1163 /* For options set at the beginning of the pattern, pcre puts them into
1164 * compile options, e.g. "(?i)foo" will make the pcre structure store
1165 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1166 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1167 compile_options = pcre_compile_options;
1169 if (!(compile_options & G_REGEX_DUPNAMES))
1171 gboolean jchanged = FALSE;
1172 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1174 compile_options |= G_REGEX_DUPNAMES;
1177 regex = g_new0 (GRegex, 1);
1178 regex->ref_count = 1;
1179 regex->pattern = g_strdup (pattern);
1180 regex->pcre_re = re;
1181 regex->compile_opts = compile_options;
1182 regex->match_opts = match_options;
1186 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1189 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1190 G_REGEX_ERROR_OPTIMIZE,
1191 _("Error while optimizing "
1192 "regular expression %s: %s"),
1195 g_propagate_error (error, tmp_error);
1197 g_regex_unref (regex);
1206 * g_regex_get_pattern:
1207 * @regex: a #GRegex structure
1209 * Gets the pattern string associated with @regex, i.e. a copy of
1210 * the string passed to g_regex_new().
1212 * Returns: the pattern of @regex
1217 g_regex_get_pattern (const GRegex *regex)
1219 g_return_val_if_fail (regex != NULL, NULL);
1221 return regex->pattern;
1225 * g_regex_get_max_backref:
1228 * Returns the number of the highest back reference
1229 * in the pattern, or 0 if the pattern does not contain
1232 * Returns: the number of the highest back reference
1237 g_regex_get_max_backref (const GRegex *regex)
1241 pcre_fullinfo (regex->pcre_re, regex->extra,
1242 PCRE_INFO_BACKREFMAX, &value);
1248 * g_regex_get_capture_count:
1251 * Returns the number of capturing subpatterns in the pattern.
1253 * Returns: the number of capturing subpatterns
1258 g_regex_get_capture_count (const GRegex *regex)
1262 pcre_fullinfo (regex->pcre_re, regex->extra,
1263 PCRE_INFO_CAPTURECOUNT, &value);
1269 * g_regex_get_compile_flags:
1272 * Returns the compile options that @regex was created with.
1274 * Returns: flags from #GRegexCompileFlags
1279 g_regex_get_compile_flags (const GRegex *regex)
1281 g_return_val_if_fail (regex != NULL, 0);
1283 return regex->compile_opts;
1287 * g_regex_get_match_flags:
1290 * Returns the match options that @regex was created with.
1292 * Returns: flags from #GRegexMatchFlags
1297 g_regex_get_match_flags (const GRegex *regex)
1299 g_return_val_if_fail (regex != NULL, 0);
1301 return regex->match_opts;
1305 * g_regex_match_simple:
1306 * @pattern: the regular expression
1307 * @string: the string to scan for matches
1308 * @compile_options: compile options for the regular expression, or 0
1309 * @match_options: match options, or 0
1311 * Scans for a match in @string for @pattern.
1313 * This function is equivalent to g_regex_match() but it does not
1314 * require to compile the pattern with g_regex_new(), avoiding some
1315 * lines of code when you need just to do a match without extracting
1316 * substrings, capture counts, and so on.
1318 * If this function is to be called on the same @pattern more than
1319 * once, it's more efficient to compile the pattern once with
1320 * g_regex_new() and then use g_regex_match().
1322 * Returns: %TRUE if the string matched, %FALSE otherwise
1327 g_regex_match_simple (const gchar *pattern,
1328 const gchar *string,
1329 GRegexCompileFlags compile_options,
1330 GRegexMatchFlags match_options)
1335 regex = g_regex_new (pattern, compile_options, 0, NULL);
1338 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1339 g_regex_unref (regex);
1345 * @regex: a #GRegex structure from g_regex_new()
1346 * @string: the string to scan for matches
1347 * @match_options: match options
1348 * @match_info: (out) (allow-none): pointer to location where to store
1349 * the #GMatchInfo, or %NULL if you do not need it
1351 * Scans for a match in string for the pattern in @regex.
1352 * The @match_options are combined with the match options specified
1353 * when the @regex structure was created, letting you have more
1354 * flexibility in reusing #GRegex structures.
1356 * A #GMatchInfo structure, used to get information on the match,
1357 * is stored in @match_info if not %NULL. Note that if @match_info
1358 * is not %NULL then it is created even if the function returns %FALSE,
1359 * i.e. you must free it regardless if regular expression actually matched.
1361 * To retrieve all the non-overlapping matches of the pattern in
1362 * string you can use g_match_info_next().
1366 * print_uppercase_words (const gchar *string)
1368 * /* Print all uppercase-only words. */
1370 * GMatchInfo *match_info;
1372 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1373 * g_regex_match (regex, string, 0, &match_info);
1374 * while (g_match_info_matches (match_info))
1376 * gchar *word = g_match_info_fetch (match_info, 0);
1377 * g_print ("Found: %s\n", word);
1379 * g_match_info_next (match_info, NULL);
1381 * g_match_info_free (match_info);
1382 * g_regex_unref (regex);
1386 * @string is not copied and is used in #GMatchInfo internally. If
1387 * you use any #GMatchInfo method (except g_match_info_free()) after
1388 * freeing or modifying @string then the behaviour is undefined.
1390 * Returns: %TRUE is the string matched, %FALSE otherwise
1395 g_regex_match (const GRegex *regex,
1396 const gchar *string,
1397 GRegexMatchFlags match_options,
1398 GMatchInfo **match_info)
1400 return g_regex_match_full (regex, string, -1, 0, match_options,
1405 * g_regex_match_full:
1406 * @regex: a #GRegex structure from g_regex_new()
1407 * @string: (array length=string_len): the string to scan for matches
1408 * @string_len: the length of @string, or -1 if @string is nul-terminated
1409 * @start_position: starting index of the string to match
1410 * @match_options: match options
1411 * @match_info: (out) (allow-none): pointer to location where to store
1412 * the #GMatchInfo, or %NULL if you do not need it
1413 * @error: location to store the error occuring, or %NULL to ignore errors
1415 * Scans for a match in string for the pattern in @regex.
1416 * The @match_options are combined with the match options specified
1417 * when the @regex structure was created, letting you have more
1418 * flexibility in reusing #GRegex structures.
1420 * Setting @start_position differs from just passing over a shortened
1421 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1422 * that begins with any kind of lookbehind assertion, such as "\b".
1424 * A #GMatchInfo structure, used to get information on the match, is
1425 * stored in @match_info if not %NULL. Note that if @match_info is
1426 * not %NULL then it is created even if the function returns %FALSE,
1427 * i.e. you must free it regardless if regular expression actually
1430 * @string is not copied and is used in #GMatchInfo internally. If
1431 * you use any #GMatchInfo method (except g_match_info_free()) after
1432 * freeing or modifying @string then the behaviour is undefined.
1434 * To retrieve all the non-overlapping matches of the pattern in
1435 * string you can use g_match_info_next().
1439 * print_uppercase_words (const gchar *string)
1441 * /* Print all uppercase-only words. */
1443 * GMatchInfo *match_info;
1444 * GError *error = NULL;
1446 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1447 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1448 * while (g_match_info_matches (match_info))
1450 * gchar *word = g_match_info_fetch (match_info, 0);
1451 * g_print ("Found: %s\n", word);
1453 * g_match_info_next (match_info, &error);
1455 * g_match_info_free (match_info);
1456 * g_regex_unref (regex);
1457 * if (error != NULL)
1459 * g_printerr ("Error while matching: %s\n", error->message);
1460 * g_error_free (error);
1465 * Returns: %TRUE is the string matched, %FALSE otherwise
1470 g_regex_match_full (const GRegex *regex,
1471 const gchar *string,
1473 gint start_position,
1474 GRegexMatchFlags match_options,
1475 GMatchInfo **match_info,
1481 g_return_val_if_fail (regex != NULL, FALSE);
1482 g_return_val_if_fail (string != NULL, FALSE);
1483 g_return_val_if_fail (start_position >= 0, FALSE);
1484 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1485 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1487 info = match_info_new (regex, string, string_len, start_position,
1488 match_options, FALSE);
1489 match_ok = g_match_info_next (info, error);
1490 if (match_info != NULL)
1493 g_match_info_free (info);
1499 * g_regex_match_all:
1500 * @regex: a #GRegex structure from g_regex_new()
1501 * @string: the string to scan for matches
1502 * @match_options: match options
1503 * @match_info: (out) (allow-none): pointer to location where to store
1504 * the #GMatchInfo, or %NULL if you do not need it
1506 * Using the standard algorithm for regular expression matching only
1507 * the longest match in the string is retrieved. This function uses
1508 * a different algorithm so it can retrieve all the possible matches.
1509 * For more documentation see g_regex_match_all_full().
1511 * A #GMatchInfo structure, used to get information on the match, is
1512 * stored in @match_info if not %NULL. Note that if @match_info is
1513 * not %NULL then it is created even if the function returns %FALSE,
1514 * i.e. you must free it regardless if regular expression actually
1517 * @string is not copied and is used in #GMatchInfo internally. If
1518 * you use any #GMatchInfo method (except g_match_info_free()) after
1519 * freeing or modifying @string then the behaviour is undefined.
1521 * Returns: %TRUE is the string matched, %FALSE otherwise
1526 g_regex_match_all (const GRegex *regex,
1527 const gchar *string,
1528 GRegexMatchFlags match_options,
1529 GMatchInfo **match_info)
1531 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1536 * g_regex_match_all_full:
1537 * @regex: a #GRegex structure from g_regex_new()
1538 * @string: (array length=string_len): the string to scan for matches
1539 * @string_len: the length of @string, or -1 if @string is nul-terminated
1540 * @start_position: starting index of the string to match
1541 * @match_options: match options
1542 * @match_info: (out) (allow-none): pointer to location where to store
1543 * the #GMatchInfo, or %NULL if you do not need it
1544 * @error: location to store the error occuring, or %NULL to ignore errors
1546 * Using the standard algorithm for regular expression matching only
1547 * the longest match in the string is retrieved, it is not possibile
1548 * to obtain all the available matches. For instance matching
1549 * "<a> <b> <c>" against the pattern "<.*>"
1550 * you get "<a> <b> <c>".
1552 * This function uses a different algorithm (called DFA, i.e. deterministic
1553 * finite automaton), so it can retrieve all the possible matches, all
1554 * starting at the same point in the string. For instance matching
1555 * "<a> <b> <c>" against the pattern "<.*>"
1556 * you would obtain three matches: "<a> <b> <c>",
1557 * "<a> <b>" and "<a>".
1559 * The number of matched strings is retrieved using
1560 * g_match_info_get_match_count(). To obtain the matched strings and
1561 * their position you can use, respectively, g_match_info_fetch() and
1562 * g_match_info_fetch_pos(). Note that the strings are returned in
1563 * reverse order of length; that is, the longest matching string is
1566 * Note that the DFA algorithm is slower than the standard one and it
1567 * is not able to capture substrings, so backreferences do not work.
1569 * Setting @start_position differs from just passing over a shortened
1570 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1571 * that begins with any kind of lookbehind assertion, such as "\b".
1573 * A #GMatchInfo structure, used to get information on the match, is
1574 * stored in @match_info if not %NULL. Note that if @match_info is
1575 * not %NULL then it is created even if the function returns %FALSE,
1576 * i.e. you must free it regardless if regular expression actually
1579 * @string is not copied and is used in #GMatchInfo internally. If
1580 * you use any #GMatchInfo method (except g_match_info_free()) after
1581 * freeing or modifying @string then the behaviour is undefined.
1583 * Returns: %TRUE is the string matched, %FALSE otherwise
1588 g_regex_match_all_full (const GRegex *regex,
1589 const gchar *string,
1591 gint start_position,
1592 GRegexMatchFlags match_options,
1593 GMatchInfo **match_info,
1599 g_return_val_if_fail (regex != NULL, FALSE);
1600 g_return_val_if_fail (string != NULL, FALSE);
1601 g_return_val_if_fail (start_position >= 0, FALSE);
1602 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1603 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1605 info = match_info_new (regex, string, string_len, start_position,
1606 match_options, TRUE);
1612 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1613 info->string, info->string_len,
1615 regex->match_opts | match_options,
1616 info->offsets, info->n_offsets,
1617 info->workspace, info->n_workspace);
1618 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1620 /* info->workspace is too small. */
1621 info->n_workspace *= 2;
1622 info->workspace = g_realloc (info->workspace,
1623 info->n_workspace * sizeof (gint));
1626 else if (info->matches == 0)
1628 /* info->offsets is too small. */
1629 info->n_offsets *= 2;
1630 info->offsets = g_realloc (info->offsets,
1631 info->n_offsets * sizeof (gint));
1634 else if (IS_PCRE_ERROR (info->matches))
1636 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1637 _("Error while matching regular expression %s: %s"),
1638 regex->pattern, match_error (info->matches));
1642 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1645 if (match_info != NULL)
1648 g_match_info_free (info);
1650 return info->matches >= 0;
1654 * g_regex_get_string_number:
1655 * @regex: #GRegex structure
1656 * @name: name of the subexpression
1658 * Retrieves the number of the subexpression named @name.
1660 * Returns: The number of the subexpression or -1 if @name
1666 g_regex_get_string_number (const GRegex *regex,
1671 g_return_val_if_fail (regex != NULL, -1);
1672 g_return_val_if_fail (name != NULL, -1);
1674 num = pcre_get_stringnumber (regex->pcre_re, name);
1675 if (num == PCRE_ERROR_NOSUBSTRING)
1682 * g_regex_split_simple:
1683 * @pattern: the regular expression
1684 * @string: the string to scan for matches
1685 * @compile_options: compile options for the regular expression, or 0
1686 * @match_options: match options, or 0
1688 * Breaks the string on the pattern, and returns an array of
1689 * the tokens. If the pattern contains capturing parentheses,
1690 * then the text for each of the substrings will also be returned.
1691 * If the pattern does not match anywhere in the string, then the
1692 * whole string is returned as the first token.
1694 * This function is equivalent to g_regex_split() but it does
1695 * not require to compile the pattern with g_regex_new(), avoiding
1696 * some lines of code when you need just to do a split without
1697 * extracting substrings, capture counts, and so on.
1699 * If this function is to be called on the same @pattern more than
1700 * once, it's more efficient to compile the pattern once with
1701 * g_regex_new() and then use g_regex_split().
1703 * As a special case, the result of splitting the empty string ""
1704 * is an empty vector, not a vector containing a single string.
1705 * The reason for this special case is that being able to represent
1706 * a empty vector is typically more useful than consistent handling
1707 * of empty elements. If you do need to represent empty elements,
1708 * you'll need to check for the empty string before calling this
1711 * A pattern that can match empty strings splits @string into
1712 * separate characters wherever it matches the empty string between
1713 * characters. For example splitting "ab c" using as a separator
1714 * "\s*", you will get "a", "b" and "c".
1716 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1721 g_regex_split_simple (const gchar *pattern,
1722 const gchar *string,
1723 GRegexCompileFlags compile_options,
1724 GRegexMatchFlags match_options)
1729 regex = g_regex_new (pattern, compile_options, 0, NULL);
1732 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1733 g_regex_unref (regex);
1739 * @regex: a #GRegex structure
1740 * @string: the string to split with the pattern
1741 * @match_options: match time option flags
1743 * Breaks the string on the pattern, and returns an array of the tokens.
1744 * If the pattern contains capturing parentheses, then the text for each
1745 * of the substrings will also be returned. If the pattern does not match
1746 * anywhere in the string, then the whole string is returned as the first
1749 * As a special case, the result of splitting the empty string "" is an
1750 * empty vector, not a vector containing a single string. The reason for
1751 * this special case is that being able to represent a empty vector is
1752 * typically more useful than consistent handling of empty elements. If
1753 * you do need to represent empty elements, you'll need to check for the
1754 * empty string before calling this function.
1756 * A pattern that can match empty strings splits @string into separate
1757 * characters wherever it matches the empty string between characters.
1758 * For example splitting "ab c" using as a separator "\s*", you will get
1761 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1766 g_regex_split (const GRegex *regex,
1767 const gchar *string,
1768 GRegexMatchFlags match_options)
1770 return g_regex_split_full (regex, string, -1, 0,
1771 match_options, 0, NULL);
1775 * g_regex_split_full:
1776 * @regex: a #GRegex structure
1777 * @string: (array length=string_len): the string to split with the pattern
1778 * @string_len: the length of @string, or -1 if @string is nul-terminated
1779 * @start_position: starting index of the string to match
1780 * @match_options: match time option flags
1781 * @max_tokens: the maximum number of tokens to split @string into.
1782 * If this is less than 1, the string is split completely
1783 * @error: return location for a #GError
1785 * Breaks the string on the pattern, and returns an array of the tokens.
1786 * If the pattern contains capturing parentheses, then the text for each
1787 * of the substrings will also be returned. If the pattern does not match
1788 * anywhere in the string, then the whole string is returned as the first
1791 * As a special case, the result of splitting the empty string "" is an
1792 * empty vector, not a vector containing a single string. The reason for
1793 * this special case is that being able to represent a empty vector is
1794 * typically more useful than consistent handling of empty elements. If
1795 * you do need to represent empty elements, you'll need to check for the
1796 * empty string before calling this function.
1798 * A pattern that can match empty strings splits @string into separate
1799 * characters wherever it matches the empty string between characters.
1800 * For example splitting "ab c" using as a separator "\s*", you will get
1803 * Setting @start_position differs from just passing over a shortened
1804 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1805 * that begins with any kind of lookbehind assertion, such as "\b".
1807 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1812 g_regex_split_full (const GRegex *regex,
1813 const gchar *string,
1815 gint start_position,
1816 GRegexMatchFlags match_options,
1820 GError *tmp_error = NULL;
1821 GMatchInfo *match_info;
1826 /* position of the last separator. */
1827 gint last_separator_end;
1828 /* was the last match 0 bytes long? */
1829 gboolean last_match_is_empty;
1830 /* the returned array of char **s */
1831 gchar **string_list;
1833 g_return_val_if_fail (regex != NULL, NULL);
1834 g_return_val_if_fail (string != NULL, NULL);
1835 g_return_val_if_fail (start_position >= 0, NULL);
1836 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1837 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1839 if (max_tokens <= 0)
1840 max_tokens = G_MAXINT;
1843 string_len = strlen (string);
1845 /* zero-length string */
1846 if (string_len - start_position == 0)
1847 return g_new0 (gchar *, 1);
1849 if (max_tokens == 1)
1851 string_list = g_new0 (gchar *, 2);
1852 string_list[0] = g_strndup (&string[start_position],
1853 string_len - start_position);
1859 last_separator_end = start_position;
1860 last_match_is_empty = FALSE;
1862 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1863 match_options, &match_info, &tmp_error);
1864 while (tmp_error == NULL)
1868 last_match_is_empty =
1869 (match_info->offsets[0] == match_info->offsets[1]);
1871 /* we need to skip empty separators at the same position of the end
1872 * of another separator. e.g. the string is "a b" and the separator
1873 * is " *", so from 1 to 2 we have a match and at position 2 we have
1874 * an empty match. */
1875 if (last_separator_end != match_info->offsets[1])
1880 token = g_strndup (string + last_separator_end,
1881 match_info->offsets[0] - last_separator_end);
1882 list = g_list_prepend (list, token);
1885 /* if there were substrings, these need to be added to
1887 match_count = g_match_info_get_match_count (match_info);
1888 if (match_count > 1)
1890 for (i = 1; i < match_count; i++)
1891 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1897 /* if there was no match, copy to end of string. */
1898 if (!last_match_is_empty)
1900 gchar *token = g_strndup (string + last_separator_end,
1901 match_info->string_len - last_separator_end);
1902 list = g_list_prepend (list, token);
1904 /* no more tokens, end the loop. */
1908 /* -1 to leave room for the last part. */
1909 if (token_count >= max_tokens - 1)
1911 /* we have reached the maximum number of tokens, so we copy
1912 * the remaining part of the string. */
1913 if (last_match_is_empty)
1915 /* the last match was empty, so we have moved one char
1916 * after the real position to avoid empty matches at the
1918 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1920 /* the if is needed in the case we have terminated the available
1921 * tokens, but we are at the end of the string, so there are no
1922 * characters left to copy. */
1923 if (string_len > match_info->pos)
1925 gchar *token = g_strndup (string + match_info->pos,
1926 string_len - match_info->pos);
1927 list = g_list_prepend (list, token);
1933 last_separator_end = match_info->pos;
1934 if (last_match_is_empty)
1935 /* if the last match was empty, g_match_info_next() has moved
1936 * forward to avoid infinite loops, but we still need to copy that
1938 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1940 match_ok = g_match_info_next (match_info, &tmp_error);
1942 g_match_info_free (match_info);
1943 if (tmp_error != NULL)
1945 g_propagate_error (error, tmp_error);
1946 g_list_foreach (list, (GFunc)g_free, NULL);
1948 match_info->pos = -1;
1952 string_list = g_new (gchar *, g_list_length (list) + 1);
1954 for (last = g_list_last (list); last; last = g_list_previous (last))
1955 string_list[i++] = last->data;
1956 string_list[i] = NULL;
1965 REPL_TYPE_CHARACTER,
1966 REPL_TYPE_SYMBOLIC_REFERENCE,
1967 REPL_TYPE_NUMERIC_REFERENCE,
1968 REPL_TYPE_CHANGE_CASE
1973 CHANGE_CASE_NONE = 1 << 0,
1974 CHANGE_CASE_UPPER = 1 << 1,
1975 CHANGE_CASE_LOWER = 1 << 2,
1976 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1977 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1978 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1979 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1980 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1983 struct _InterpolationData
1989 ChangeCase change_case;
1993 free_interpolation_data (InterpolationData *data)
1995 g_free (data->text);
1999 static const gchar *
2000 expand_escape (const gchar *replacement,
2002 InterpolationData *data,
2007 const gchar *error_detail;
2009 GError *tmp_error = NULL;
2017 data->type = REPL_TYPE_CHARACTER;
2022 data->type = REPL_TYPE_CHARACTER;
2027 data->type = REPL_TYPE_CHARACTER;
2032 data->type = REPL_TYPE_CHARACTER;
2037 data->type = REPL_TYPE_CHARACTER;
2042 data->type = REPL_TYPE_CHARACTER;
2047 data->type = REPL_TYPE_CHARACTER;
2052 data->type = REPL_TYPE_CHARACTER;
2062 h = g_ascii_xdigit_value (*p);
2065 error_detail = _("hexadecimal digit or '}' expected");
2076 for (i = 0; i < 2; i++)
2078 h = g_ascii_xdigit_value (*p);
2081 error_detail = _("hexadecimal digit expected");
2088 data->type = REPL_TYPE_STRING;
2089 data->text = g_new0 (gchar, 8);
2090 g_unichar_to_utf8 (x, data->text);
2094 data->type = REPL_TYPE_CHANGE_CASE;
2095 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2099 data->type = REPL_TYPE_CHANGE_CASE;
2100 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2104 data->type = REPL_TYPE_CHANGE_CASE;
2105 data->change_case = CHANGE_CASE_LOWER;
2109 data->type = REPL_TYPE_CHANGE_CASE;
2110 data->change_case = CHANGE_CASE_UPPER;
2114 data->type = REPL_TYPE_CHANGE_CASE;
2115 data->change_case = CHANGE_CASE_NONE;
2121 error_detail = _("missing '<' in symbolic reference");
2130 error_detail = _("unfinished symbolic reference");
2137 error_detail = _("zero-length symbolic reference");
2140 if (g_ascii_isdigit (*q))
2145 h = g_ascii_digit_value (*q);
2148 error_detail = _("digit expected");
2157 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2164 if (!g_ascii_isalnum (*r))
2166 error_detail = _("illegal symbolic reference");
2173 data->text = g_strndup (q, p - q);
2174 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2179 /* if \0 is followed by a number is an octal number representing a
2180 * character, else it is a numeric reference. */
2181 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2184 p = g_utf8_next_char (p);
2197 for (i = 0; i < 3; i++)
2199 h = g_ascii_digit_value (*p);
2209 if (i == 2 && base == 10)
2215 if (base == 8 || i == 3)
2217 data->type = REPL_TYPE_STRING;
2218 data->text = g_new0 (gchar, 8);
2219 g_unichar_to_utf8 (x, data->text);
2223 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2228 error_detail = _("stray final '\\'");
2232 error_detail = _("unknown escape sequence");
2239 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2240 tmp_error = g_error_new (G_REGEX_ERROR,
2241 G_REGEX_ERROR_REPLACE,
2242 _("Error while parsing replacement "
2243 "text \"%s\" at char %lu: %s"),
2245 (gulong)(p - replacement),
2247 g_propagate_error (error, tmp_error);
2253 split_replacement (const gchar *replacement,
2257 InterpolationData *data;
2258 const gchar *p, *start;
2260 start = p = replacement;
2265 data = g_new0 (InterpolationData, 1);
2266 start = p = expand_escape (replacement, p, data, error);
2269 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2271 free_interpolation_data (data);
2275 list = g_list_prepend (list, data);
2280 if (*p == '\\' || *p == '\0')
2284 data = g_new0 (InterpolationData, 1);
2285 data->text = g_strndup (start, p - start);
2286 data->type = REPL_TYPE_STRING;
2287 list = g_list_prepend (list, data);
2293 return g_list_reverse (list);
2296 /* Change the case of c based on change_case. */
2297 #define CHANGE_CASE(c, change_case) \
2298 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2299 g_unichar_tolower (c) : \
2300 g_unichar_toupper (c))
2303 string_append (GString *string,
2305 ChangeCase *change_case)
2309 if (text[0] == '\0')
2312 if (*change_case == CHANGE_CASE_NONE)
2314 g_string_append (string, text);
2316 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2318 c = g_utf8_get_char (text);
2319 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2320 g_string_append (string, g_utf8_next_char (text));
2321 *change_case = CHANGE_CASE_NONE;
2325 while (*text != '\0')
2327 c = g_utf8_get_char (text);
2328 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2329 text = g_utf8_next_char (text);
2335 interpolate_replacement (const GMatchInfo *match_info,
2340 InterpolationData *idata;
2342 ChangeCase change_case = CHANGE_CASE_NONE;
2344 for (list = data; list; list = list->next)
2347 switch (idata->type)
2349 case REPL_TYPE_STRING:
2350 string_append (result, idata->text, &change_case);
2352 case REPL_TYPE_CHARACTER:
2353 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2354 if (change_case & CHANGE_CASE_SINGLE_MASK)
2355 change_case = CHANGE_CASE_NONE;
2357 case REPL_TYPE_NUMERIC_REFERENCE:
2358 match = g_match_info_fetch (match_info, idata->num);
2361 string_append (result, match, &change_case);
2365 case REPL_TYPE_SYMBOLIC_REFERENCE:
2366 match = g_match_info_fetch_named (match_info, idata->text);
2369 string_append (result, match, &change_case);
2373 case REPL_TYPE_CHANGE_CASE:
2374 change_case = idata->change_case;
2382 /* whether actual match_info is needed for replacement, i.e.
2383 * whether there are references
2386 interpolation_list_needs_match (GList *list)
2388 while (list != NULL)
2390 InterpolationData *data = list->data;
2392 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2393 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2406 * @regex: a #GRegex structure
2407 * @string: (array length=string_len): the string to perform matches against
2408 * @string_len: the length of @string, or -1 if @string is nul-terminated
2409 * @start_position: starting index of the string to match
2410 * @replacement: text to replace each match with
2411 * @match_options: options for the match
2412 * @error: location to store the error occuring, or %NULL to ignore errors
2414 * Replaces all occurrences of the pattern in @regex with the
2415 * replacement text. Backreferences of the form '\number' or
2416 * '\g<number>' in the replacement text are interpolated by the
2417 * number-th captured subexpression of the match, '\g<name>' refers
2418 * to the captured subexpression with the given name. '\0' refers to the
2419 * complete match, but '\0' followed by a number is the octal representation
2420 * of a character. To include a literal '\' in the replacement, write '\\'.
2421 * There are also escapes that changes the case of the following text:
2424 * <varlistentry><term>\l</term>
2426 * <para>Convert to lower case the next character</para>
2429 * <varlistentry><term>\u</term>
2431 * <para>Convert to upper case the next character</para>
2434 * <varlistentry><term>\L</term>
2436 * <para>Convert to lower case till \E</para>
2439 * <varlistentry><term>\U</term>
2441 * <para>Convert to upper case till \E</para>
2444 * <varlistentry><term>\E</term>
2446 * <para>End case modification</para>
2451 * If you do not need to use backreferences use g_regex_replace_literal().
2453 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2454 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2455 * you can use g_regex_replace_literal().
2457 * Setting @start_position differs from just passing over a shortened
2458 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2459 * begins with any kind of lookbehind assertion, such as "\b".
2461 * Returns: a newly allocated string containing the replacements
2466 g_regex_replace (const GRegex *regex,
2467 const gchar *string,
2469 gint start_position,
2470 const gchar *replacement,
2471 GRegexMatchFlags match_options,
2476 GError *tmp_error = NULL;
2478 g_return_val_if_fail (regex != NULL, NULL);
2479 g_return_val_if_fail (string != NULL, NULL);
2480 g_return_val_if_fail (start_position >= 0, NULL);
2481 g_return_val_if_fail (replacement != NULL, NULL);
2482 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2483 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2485 list = split_replacement (replacement, &tmp_error);
2486 if (tmp_error != NULL)
2488 g_propagate_error (error, tmp_error);
2492 result = g_regex_replace_eval (regex,
2493 string, string_len, start_position,
2495 interpolate_replacement,
2498 if (tmp_error != NULL)
2499 g_propagate_error (error, tmp_error);
2501 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2508 literal_replacement (const GMatchInfo *match_info,
2512 g_string_append (result, data);
2517 * g_regex_replace_literal:
2518 * @regex: a #GRegex structure
2519 * @string: (array length=string_len): the string to perform matches against
2520 * @string_len: the length of @string, or -1 if @string is nul-terminated
2521 * @start_position: starting index of the string to match
2522 * @replacement: text to replace each match with
2523 * @match_options: options for the match
2524 * @error: location to store the error occuring, or %NULL to ignore errors
2526 * Replaces all occurrences of the pattern in @regex with the
2527 * replacement text. @replacement is replaced literally, to
2528 * include backreferences use g_regex_replace().
2530 * Setting @start_position differs from just passing over a
2531 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2532 * case of a pattern that begins with any kind of lookbehind
2533 * assertion, such as "\b".
2535 * Returns: a newly allocated string containing the replacements
2540 g_regex_replace_literal (const GRegex *regex,
2541 const gchar *string,
2543 gint start_position,
2544 const gchar *replacement,
2545 GRegexMatchFlags match_options,
2548 g_return_val_if_fail (replacement != NULL, NULL);
2549 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2551 return g_regex_replace_eval (regex,
2552 string, string_len, start_position,
2554 literal_replacement,
2555 (gpointer)replacement,
2560 * g_regex_replace_eval:
2561 * @regex: a #GRegex structure from g_regex_new()
2562 * @string (array length=string_len): string to perform matches against
2563 * @string_len: the length of @string, or -1 if @string is nul-terminated
2564 * @start_position: starting index of the string to match
2565 * @match_options: options for the match
2566 * @eval: a function to call for each match
2567 * @user_data: user data to pass to the function
2568 * @error: location to store the error occuring, or %NULL to ignore errors
2570 * Replaces occurrences of the pattern in regex with the output of
2571 * @eval for that occurrence.
2573 * Setting @start_position differs from just passing over a shortened
2574 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2575 * that begins with any kind of lookbehind assertion, such as "\b".
2577 * The following example uses g_regex_replace_eval() to replace multiple
2581 * eval_cb (const GMatchInfo *info,
2588 * match = g_match_info_fetch (info, 0);
2589 * r = g_hash_table_lookup ((GHashTable *)data, match);
2590 * g_string_append (res, r);
2602 * h = g_hash_table_new (g_str_hash, g_str_equal);
2604 * g_hash_table_insert (h, "1", "ONE");
2605 * g_hash_table_insert (h, "2", "TWO");
2606 * g_hash_table_insert (h, "3", "THREE");
2607 * g_hash_table_insert (h, "4", "FOUR");
2609 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2610 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2611 * g_hash_table_destroy (h);
2616 * Returns: a newly allocated string containing the replacements
2621 g_regex_replace_eval (const GRegex *regex,
2622 const gchar *string,
2624 gint start_position,
2625 GRegexMatchFlags match_options,
2626 GRegexEvalCallback eval,
2630 GMatchInfo *match_info;
2633 gboolean done = FALSE;
2634 GError *tmp_error = NULL;
2636 g_return_val_if_fail (regex != NULL, NULL);
2637 g_return_val_if_fail (string != NULL, NULL);
2638 g_return_val_if_fail (start_position >= 0, NULL);
2639 g_return_val_if_fail (eval != NULL, NULL);
2640 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2643 string_len = strlen (string);
2645 result = g_string_sized_new (string_len);
2647 /* run down the string making matches. */
2648 g_regex_match_full (regex, string, string_len, start_position,
2649 match_options, &match_info, &tmp_error);
2650 while (!done && g_match_info_matches (match_info))
2652 g_string_append_len (result,
2654 match_info->offsets[0] - str_pos);
2655 done = (*eval) (match_info, result, user_data);
2656 str_pos = match_info->offsets[1];
2657 g_match_info_next (match_info, &tmp_error);
2659 g_match_info_free (match_info);
2660 if (tmp_error != NULL)
2662 g_propagate_error (error, tmp_error);
2663 g_string_free (result, TRUE);
2667 g_string_append_len (result, string + str_pos, string_len - str_pos);
2668 return g_string_free (result, FALSE);
2672 * g_regex_check_replacement:
2673 * @replacement: the replacement string
2674 * @has_references: (out) (allow-none): location to store information about
2675 * references in @replacement or %NULL
2676 * @error: location to store error
2678 * Checks whether @replacement is a valid replacement string
2679 * (see g_regex_replace()), i.e. that all escape sequences in
2682 * If @has_references is not %NULL then @replacement is checked
2683 * for pattern references. For instance, replacement text 'foo\n'
2684 * does not contain references and may be evaluated without information
2685 * about actual match, but '\0\1' (whole match followed by first
2686 * subpattern) requires valid #GMatchInfo object.
2688 * Returns: whether @replacement is a valid replacement string
2693 g_regex_check_replacement (const gchar *replacement,
2694 gboolean *has_references,
2700 list = split_replacement (replacement, &tmp);
2704 g_propagate_error (error, tmp);
2709 *has_references = interpolation_list_needs_match (list);
2711 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2718 * g_regex_escape_string:
2719 * @string: (array length=length): the string to escape
2720 * @length: the length of @string, or -1 if @string is nul-terminated
2722 * Escapes the special characters used for regular expressions
2723 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2724 * function is useful to dynamically generate regular expressions.
2726 * @string can contain nul characters that are replaced with "\0",
2727 * in this case remember to specify the correct length of @string
2730 * Returns: a newly-allocated escaped string
2735 g_regex_escape_string (const gchar *string,
2739 const char *p, *piece_start, *end;
2741 g_return_val_if_fail (string != NULL, NULL);
2744 length = strlen (string);
2746 end = string + length;
2747 p = piece_start = string;
2748 escaped = g_string_sized_new (length + 1);
2769 if (p != piece_start)
2770 /* copy the previous piece. */
2771 g_string_append_len (escaped, piece_start, p - piece_start);
2772 g_string_append_c (escaped, '\\');
2774 g_string_append_c (escaped, '0');
2776 g_string_append_c (escaped, *p);
2780 p = g_utf8_next_char (p);
2785 if (piece_start < end)
2786 g_string_append_len (escaped, piece_start, end - piece_start);
2788 return g_string_free (escaped, FALSE);