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"
36 /* PCRE 7.3 does not contain the definition of PCRE_ERROR_NULLWSLIMIT */
37 #ifndef PCRE_ERROR_NULLWSLIMIT
38 #define PCRE_ERROR_NULLWSLIMIT (-22)
42 /* Mask of all the possible values for GRegexCompileFlags. */
43 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
48 G_REGEX_DOLLAR_ENDONLY | \
51 G_REGEX_NO_AUTO_CAPTURE | \
54 G_REGEX_NEWLINE_CR | \
55 G_REGEX_NEWLINE_LF | \
58 /* Mask of all the possible values for GRegexMatchFlags. */
59 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
60 G_REGEX_MATCH_NOTBOL | \
61 G_REGEX_MATCH_NOTEOL | \
62 G_REGEX_MATCH_NOTEMPTY | \
63 G_REGEX_MATCH_PARTIAL | \
64 G_REGEX_MATCH_NEWLINE_CR | \
65 G_REGEX_MATCH_NEWLINE_LF | \
66 G_REGEX_MATCH_NEWLINE_CRLF | \
67 G_REGEX_MATCH_NEWLINE_ANY)
69 /* if the string is in UTF-8 use g_utf8_ functions, else use
71 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
72 g_utf8_next_char (s) : \
74 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
75 g_utf8_prev_char (s) : \
80 GRegex *regex; /* the regex */
81 GRegexMatchFlags match_opts; /* options used at match time on the regex */
82 gint matches; /* number of matching sub patterns */
83 gint pos; /* position in the string where last match left off */
84 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
85 gint n_offsets; /* number of offsets */
86 gint *workspace; /* workspace for pcre_dfa_exec() */
87 gint n_workspace; /* number of workspace elements */
88 const gchar *string; /* string passed to the match function */
89 gssize string_len; /* length of string */
94 volatile gint ref_count; /* the ref count for the immutable part */
95 gchar *pattern; /* the pattern */
96 pcre *pcre_re; /* compiled form of the pattern */
97 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
98 GRegexMatchFlags match_opts; /* options used at match time on the regex */
99 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
102 /* TRUE if ret is an error code, FALSE otherwise. */
103 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
105 typedef struct _InterpolationData InterpolationData;
106 static gboolean interpolation_list_needs_match (GList *list);
107 static gboolean interpolate_replacement (const GMatchInfo *match_info,
110 static GList *split_replacement (const gchar *replacement,
112 static void free_interpolation_data (InterpolationData *data);
116 match_error (gint errcode)
120 case PCRE_ERROR_NOMATCH:
123 case PCRE_ERROR_NULL:
124 /* NULL argument, this should not happen in GRegex */
125 g_warning ("A NULL argument was passed to PCRE");
127 case PCRE_ERROR_BADOPTION:
128 return "bad options";
129 case PCRE_ERROR_BADMAGIC:
130 return _("corrupted object");
131 case PCRE_ERROR_UNKNOWN_OPCODE:
132 return N_("internal error or corrupted object");
133 case PCRE_ERROR_NOMEMORY:
134 return _("out of memory");
135 case PCRE_ERROR_NOSUBSTRING:
136 /* not used by pcre_exec() */
138 case PCRE_ERROR_MATCHLIMIT:
139 return _("backtracking limit reached");
140 case PCRE_ERROR_CALLOUT:
141 /* callouts are not implemented */
143 case PCRE_ERROR_BADUTF8:
144 case PCRE_ERROR_BADUTF8_OFFSET:
145 /* we do not check if strings are valid */
147 case PCRE_ERROR_PARTIAL:
150 case PCRE_ERROR_BADPARTIAL:
151 return _("the pattern contains items not supported for partial matching");
152 case PCRE_ERROR_INTERNAL:
153 return _("internal error");
154 case PCRE_ERROR_BADCOUNT:
155 /* negative ovecsize, this should not happen in GRegex */
156 g_warning ("A negative ovecsize was passed to PCRE");
158 case PCRE_ERROR_DFA_UITEM:
159 return _("the pattern contains items not supported for partial matching");
160 case PCRE_ERROR_DFA_UCOND:
161 return _("back references as conditions are not supported for partial matching");
162 case PCRE_ERROR_DFA_UMLIMIT:
163 /* the match_field field is not used in GRegex */
165 case PCRE_ERROR_DFA_WSSIZE:
166 /* handled expanding the workspace */
168 case PCRE_ERROR_DFA_RECURSE:
169 case PCRE_ERROR_RECURSIONLIMIT:
170 return _("recursion limit reached");
171 case PCRE_ERROR_NULLWSLIMIT:
172 return _("workspace limit for empty substrings reached");
173 case PCRE_ERROR_BADNEWLINE:
174 return _("invalid combination of newline flags");
178 return _("unknown error");
182 translate_compile_error (gint *errcode, const gchar **errmsg)
184 /* Compile errors are created adding 100 to the error code returned
186 * If errcode is known we put the translatable error message in
187 * erromsg. If errcode is unknown we put the generic
188 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
189 * untranslated error message returned by PCRE.
190 * Note that there can be more PCRE errors with the same GRegexError
191 * and that some PCRE errors are useless for us.
197 case G_REGEX_ERROR_STRAY_BACKSLASH:
198 *errmsg = _("\\ at end of pattern");
200 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
201 *errmsg = _("\\c at end of pattern");
203 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
204 *errmsg = _("unrecognized character follows \\");
207 /* A number of Perl escapes are not handled by PCRE.
208 * Therefore it explicitly raises ERR37.
210 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
211 *errmsg = _("case-changing escapes (\\l, \\L, \\u, \\U) are not allowed here");
213 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
214 *errmsg = _("numbers out of order in {} quantifier");
216 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
217 *errmsg = _("number too big in {} quantifier");
219 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
220 *errmsg = _("missing terminating ] for character class");
222 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
223 *errmsg = _("invalid escape sequence in character class");
225 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
226 *errmsg = _("range out of order in character class");
228 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
229 *errmsg = _("nothing to repeat");
231 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
232 *errmsg = _("unrecognized character after (?");
235 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
236 *errmsg = _("unrecognized character after (?<");
239 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
240 *errmsg = _("unrecognized character after (?P");
242 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
243 *errmsg = _("POSIX named classes are supported only within a class");
245 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
246 *errmsg = _("missing terminating )");
249 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
250 *errmsg = _(") without opening (");
253 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
254 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
255 * sequences here, '(?-54' would be an example for the second group.
257 *errmsg = _("(?R or (?[+-]digits must be followed by )");
259 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
260 *errmsg = _("reference to non-existent subpattern");
262 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
263 *errmsg = _("missing ) after comment");
265 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
266 *errmsg = _("regular expression too large");
268 case G_REGEX_ERROR_MEMORY_ERROR:
269 *errmsg = _("failed to get memory");
271 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
272 *errmsg = _("lookbehind assertion is not fixed length");
274 case G_REGEX_ERROR_MALFORMED_CONDITION:
275 *errmsg = _("malformed number or name after (?(");
277 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
278 *errmsg = _("conditional group contains more than two branches");
280 case G_REGEX_ERROR_ASSERTION_EXPECTED:
281 *errmsg = _("assertion expected after (?(");
283 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
284 *errmsg = _("unknown POSIX class name");
286 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
287 *errmsg = _("POSIX collating elements are not supported");
289 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
290 *errmsg = _("character value in \\x{...} sequence is too large");
292 case G_REGEX_ERROR_INVALID_CONDITION:
293 *errmsg = _("invalid condition (?(0)");
295 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
296 *errmsg = _("\\C not allowed in lookbehind assertion");
298 case G_REGEX_ERROR_INFINITE_LOOP:
299 *errmsg = _("recursive call could loop indefinitely");
301 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
302 *errmsg = _("missing terminator in subpattern name");
304 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
305 *errmsg = _("two named subpatterns have the same name");
307 case G_REGEX_ERROR_MALFORMED_PROPERTY:
308 *errmsg = _("malformed \\P or \\p sequence");
310 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
311 *errmsg = _("unknown property name after \\P or \\p");
313 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
314 *errmsg = _("subpattern name is too long (maximum 32 characters)");
316 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
317 *errmsg = _("too many named subpatterns (maximum 10,000)");
319 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
320 *errmsg = _("octal value is greater than \\377");
322 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
323 *errmsg = _("DEFINE group contains more than one branch");
325 case G_REGEX_ERROR_DEFINE_REPETION:
326 *errmsg = _("repeating a DEFINE group is not allowed");
328 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
329 *errmsg = _("inconsistent NEWLINE options");
331 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
332 *errmsg = _("\\g is not followed by a braced name or an optionally "
333 "braced non-zero number");
336 *errcode = G_REGEX_ERROR_INTERNAL;
337 *errmsg = _("unexpected repeat");
340 *errcode = G_REGEX_ERROR_INTERNAL;
341 *errmsg = _("code overflow");
344 *errcode = G_REGEX_ERROR_INTERNAL;
345 *errmsg = _("overran compiling workspace");
348 *errcode = G_REGEX_ERROR_INTERNAL;
349 *errmsg = _("previously-checked referenced subpattern not found");
352 /* This should not happen as we never pass a NULL erroffset */
353 g_warning ("erroffset passed as NULL");
354 *errcode = G_REGEX_ERROR_COMPILE;
357 /* This should not happen as we check options before passing them
358 * to pcre_compile2() */
359 g_warning ("unknown option bit(s) set");
360 *errcode = G_REGEX_ERROR_COMPILE;
365 /* These errors should not happen as we are using an UTF8-enabled PCRE
366 * and we do not check if strings are valid */
367 g_warning ("%s", *errmsg);
368 *errcode = G_REGEX_ERROR_COMPILE;
371 *errcode = G_REGEX_ERROR_COMPILE;
378 match_info_new (const GRegex *regex,
385 GMatchInfo *match_info;
388 string_len = strlen (string);
390 match_info = g_new0 (GMatchInfo, 1);
391 match_info->regex = g_regex_ref ((GRegex *)regex);
392 match_info->string = string;
393 match_info->string_len = string_len;
394 match_info->matches = PCRE_ERROR_NOMATCH;
395 match_info->pos = start_position;
396 match_info->match_opts = match_options;
400 /* These values should be enough for most cases, if they are not
401 * enough g_regex_match_all_full() will expand them. */
402 match_info->n_offsets = 24;
403 match_info->n_workspace = 100;
404 match_info->workspace = g_new (gint, match_info->n_workspace);
409 pcre_fullinfo (regex->pcre_re, regex->extra,
410 PCRE_INFO_CAPTURECOUNT, &capture_count);
411 match_info->n_offsets = (capture_count + 1) * 3;
414 match_info->offsets = g_new0 (gint, match_info->n_offsets);
415 /* Set an invalid position for the previous match. */
416 match_info->offsets[0] = -1;
417 match_info->offsets[1] = -1;
423 * g_match_info_get_regex:
424 * @match_info: a #GMatchInfo
426 * Returns #GRegex object used in @match_info. It belongs to Glib
427 * and must not be freed. Use g_regex_ref() if you need to keep it
428 * after you free @match_info object.
430 * Returns: #GRegex object used in @match_info
435 g_match_info_get_regex (const GMatchInfo *match_info)
437 g_return_val_if_fail (match_info != NULL, NULL);
438 return match_info->regex;
442 * g_match_info_get_string:
443 * @match_info: a #GMatchInfo
445 * Returns the string searched with @match_info. This is the
446 * string passed to g_regex_match() or g_regex_replace() so
447 * you may not free it before calling this function.
449 * Returns: the string searched with @match_info
454 g_match_info_get_string (const GMatchInfo *match_info)
456 g_return_val_if_fail (match_info != NULL, NULL);
457 return match_info->string;
462 * @match_info: a #GMatchInfo
464 * Frees all the memory associated with the #GMatchInfo structure.
469 g_match_info_free (GMatchInfo *match_info)
473 g_regex_unref (match_info->regex);
474 g_free (match_info->offsets);
475 g_free (match_info->workspace);
482 * @match_info: a #GMatchInfo structure
483 * @error: location to store the error occuring, or %NULL to ignore errors
485 * Scans for the next match using the same parameters of the previous
486 * call to g_regex_match_full() or g_regex_match() that returned
489 * The match is done on the string passed to the match function, so you
490 * cannot free it before calling this function.
492 * Returns: %TRUE is the string matched, %FALSE otherwise
497 g_match_info_next (GMatchInfo *match_info,
500 gint prev_match_start;
503 g_return_val_if_fail (match_info != NULL, FALSE);
504 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
505 g_return_val_if_fail (match_info->pos >= 0, FALSE);
507 prev_match_start = match_info->offsets[0];
508 prev_match_end = match_info->offsets[1];
510 match_info->matches = pcre_exec (match_info->regex->pcre_re,
511 match_info->regex->extra,
513 match_info->string_len,
515 match_info->regex->match_opts | match_info->match_opts,
517 match_info->n_offsets);
518 if (IS_PCRE_ERROR (match_info->matches))
520 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
521 _("Error while matching regular expression %s: %s"),
522 match_info->regex->pattern, match_error (match_info->matches));
526 /* avoid infinite loops if the pattern is an empty string or something
528 if (match_info->pos == match_info->offsets[1])
530 if (match_info->pos > match_info->string_len)
532 /* we have reached the end of the string */
533 match_info->pos = -1;
534 match_info->matches = PCRE_ERROR_NOMATCH;
538 match_info->pos = NEXT_CHAR (match_info->regex,
539 &match_info->string[match_info->pos]) -
544 match_info->pos = match_info->offsets[1];
547 /* it's possible to get two identical matches when we are matching
548 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
549 * the string is "RegExTest" we have:
550 * - search at position 0: match from 0 to 0
551 * - search at position 1: match from 3 to 3
552 * - search at position 3: match from 3 to 3 (duplicate)
553 * - search at position 4: match from 5 to 5
554 * - search at position 5: match from 5 to 5 (duplicate)
555 * - search at position 6: no match -> stop
556 * so we have to ignore the duplicates.
557 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
558 if (match_info->matches >= 0 &&
559 prev_match_start == match_info->offsets[0] &&
560 prev_match_end == match_info->offsets[1])
562 /* ignore this match and search the next one */
563 return g_match_info_next (match_info, error);
566 return match_info->matches >= 0;
570 * g_match_info_matches:
571 * @match_info: a #GMatchInfo structure
573 * Returns whether the previous match operation succeeded.
575 * Returns: %TRUE if the previous match operation succeeded,
581 g_match_info_matches (const GMatchInfo *match_info)
583 g_return_val_if_fail (match_info != NULL, FALSE);
585 return match_info->matches >= 0;
589 * g_match_info_get_match_count:
590 * @match_info: a #GMatchInfo structure
592 * Retrieves the number of matched substrings (including substring 0,
593 * that is the whole matched text), so 1 is returned if the pattern
594 * has no substrings in it and 0 is returned if the match failed.
596 * If the last match was obtained using the DFA algorithm, that is
597 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
598 * count is not that of the number of capturing parentheses but that of
599 * the number of matched substrings.
601 * Returns: Number of matched substrings, or -1 if an error occurred
606 g_match_info_get_match_count (const GMatchInfo *match_info)
608 g_return_val_if_fail (match_info, -1);
610 if (match_info->matches == PCRE_ERROR_NOMATCH)
613 else if (match_info->matches < PCRE_ERROR_NOMATCH)
618 return match_info->matches;
622 * g_match_info_is_partial_match:
623 * @match_info: a #GMatchInfo structure
625 * Usually if the string passed to g_regex_match*() matches as far as
626 * it goes, but is too short to match the entire pattern, %FALSE is
627 * returned. There are circumstances where it might be helpful to
628 * distinguish this case from other cases in which there is no match.
630 * Consider, for example, an application where a human is required to
631 * type in data for a field with specific formatting requirements. An
632 * example might be a date in the form ddmmmyy, defined by the pattern
633 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
634 * If the application sees the user’s keystrokes one by one, and can
635 * check that what has been typed so far is potentially valid, it is
636 * able to raise an error as soon as a mistake is made.
638 * GRegex supports the concept of partial matching by means of the
639 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
640 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
641 * for a complete match, %FALSE otherwise. But, when these functions
642 * return %FALSE, you can check if the match was partial calling
643 * g_match_info_is_partial_match().
645 * When using partial matching you cannot use g_match_info_fetch*().
647 * Because of the way certain internal optimizations are implemented
648 * the partial matching algorithm cannot be used with all patterns.
649 * So repeated single characters such as "a{2,4}" and repeated single
650 * meta-sequences such as "\d+" are not permitted if the maximum number
651 * of occurrences is greater than one. Optional items such as "\d?"
652 * (where the maximum is one) are permitted. Quantifiers with any values
653 * are permitted after parentheses, so the invalid examples above can be
654 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
655 * for a pattern that does not conform to the restrictions, matching
656 * functions return an error.
658 * Returns: %TRUE if the match was partial, %FALSE otherwise
663 g_match_info_is_partial_match (const GMatchInfo *match_info)
665 g_return_val_if_fail (match_info != NULL, FALSE);
667 return match_info->matches == PCRE_ERROR_PARTIAL;
671 * g_match_info_expand_references:
672 * @match_info: a #GMatchInfo or %NULL
673 * @string_to_expand: the string to expand
674 * @error: location to store the error occuring, or %NULL to ignore errors
676 * Returns a new string containing the text in @string_to_expand with
677 * references and escape sequences expanded. References refer to the last
678 * match done with @string against @regex and have the same syntax used by
681 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
682 * passed to g_regex_new().
684 * The backreferences are extracted from the string passed to the match
685 * function, so you cannot call this function after freeing the string.
687 * @match_info may be %NULL in which case @string_to_expand must not
688 * contain references. For instance "foo\n" does not refer to an actual
689 * pattern and '\n' merely will be replaced with \n character,
690 * while to expand "\0" (whole match) one needs the result of a match.
691 * Use g_regex_check_replacement() to find out whether @string_to_expand
692 * contains references.
694 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
699 g_match_info_expand_references (const GMatchInfo *match_info,
700 const gchar *string_to_expand,
705 GError *tmp_error = NULL;
707 g_return_val_if_fail (string_to_expand != NULL, NULL);
708 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
710 list = split_replacement (string_to_expand, &tmp_error);
711 if (tmp_error != NULL)
713 g_propagate_error (error, tmp_error);
717 if (!match_info && interpolation_list_needs_match (list))
719 g_critical ("String '%s' contains references to the match, can't "
720 "expand references without GMatchInfo object",
725 result = g_string_sized_new (strlen (string_to_expand));
726 interpolate_replacement (match_info, result, list);
728 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
731 return g_string_free (result, FALSE);
735 * g_match_info_fetch:
736 * @match_info: #GMatchInfo structure
737 * @match_num: number of the sub expression
739 * Retrieves the text matching the @match_num<!-- -->'th capturing
740 * parentheses. 0 is the full text of the match, 1 is the first paren
741 * set, 2 the second, and so on.
743 * If @match_num is a valid sub pattern but it didn't match anything
744 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
745 * string is returned.
747 * If the match was obtained using the DFA algorithm, that is using
748 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
749 * string is not that of a set of parentheses but that of a matched
750 * substring. Substrings are matched in reverse order of length, so
751 * 0 is the longest match.
753 * The string is fetched from the string passed to the match function,
754 * so you cannot call this function after freeing the string.
756 * Returns: (allow-none): The matched substring, or %NULL if an error
757 * occurred. You have to free the string yourself
762 g_match_info_fetch (const GMatchInfo *match_info,
765 /* we cannot use pcre_get_substring() because it allocates the
766 * string using pcre_malloc(). */
770 g_return_val_if_fail (match_info != NULL, NULL);
771 g_return_val_if_fail (match_num >= 0, NULL);
773 /* match_num does not exist or it didn't matched, i.e. matching "b"
774 * against "(a)?b" then group 0 is empty. */
775 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
777 else if (start == -1)
778 match = g_strdup ("");
780 match = g_strndup (&match_info->string[start], end - start);
786 * g_match_info_fetch_pos:
787 * @match_info: #GMatchInfo structure
788 * @match_num: number of the sub expression
789 * @start_pos: (out) (allow-none): pointer to location where to store
790 * the start position, or %NULL
791 * @end_pos: (out) (allow-none): pointer to location where to store
792 * the end position, or %NULL
794 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
795 * parentheses. 0 is the full text of the match, 1 is the first
796 * paren set, 2 the second, and so on.
798 * If @match_num is a valid sub pattern but it didn't match anything
799 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
800 * and @end_pos are set to -1 and %TRUE is returned.
802 * If the match was obtained using the DFA algorithm, that is using
803 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
804 * position is not that of a set of parentheses but that of a matched
805 * substring. Substrings are matched in reverse order of length, so
806 * 0 is the longest match.
808 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
809 * the position cannot be fetched, @start_pos and @end_pos are left
815 g_match_info_fetch_pos (const GMatchInfo *match_info,
820 g_return_val_if_fail (match_info != NULL, FALSE);
821 g_return_val_if_fail (match_num >= 0, FALSE);
823 /* make sure the sub expression number they're requesting is less than
824 * the total number of sub expressions that were matched. */
825 if (match_num >= match_info->matches)
828 if (start_pos != NULL)
829 *start_pos = match_info->offsets[2 * match_num];
832 *end_pos = match_info->offsets[2 * match_num + 1];
838 * Returns number of first matched subpattern with name @name.
839 * There may be more than one in case when DUPNAMES is used,
840 * and not all subpatterns with that name match;
841 * pcre_get_stringnumber() does not work in that case.
844 get_matched_substring_number (const GMatchInfo *match_info,
851 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
852 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
854 /* This code is copied from pcre_get.c: get_first_set() */
855 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
863 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
865 gint n = (entry[0] << 8) + entry[1];
866 if (match_info->offsets[n*2] >= 0)
870 return (first[0] << 8) + first[1];
874 * g_match_info_fetch_named:
875 * @match_info: #GMatchInfo structure
876 * @name: name of the subexpression
878 * Retrieves the text matching the capturing parentheses named @name.
880 * If @name is a valid sub pattern name but it didn't match anything
881 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
882 * then an empty string is returned.
884 * The string is fetched from the string passed to the match function,
885 * so you cannot call this function after freeing the string.
887 * Returns: (allow-none): The matched substring, or %NULL if an error
888 * occurred. You have to free the string yourself
893 g_match_info_fetch_named (const GMatchInfo *match_info,
896 /* we cannot use pcre_get_named_substring() because it allocates the
897 * string using pcre_malloc(). */
900 g_return_val_if_fail (match_info != NULL, NULL);
901 g_return_val_if_fail (name != NULL, NULL);
903 num = get_matched_substring_number (match_info, name);
907 return g_match_info_fetch (match_info, num);
911 * g_match_info_fetch_named_pos:
912 * @match_info: #GMatchInfo structure
913 * @name: name of the subexpression
914 * @start_pos: (out) (allow-none): pointer to location where to store
915 * the start position, or %NULL
916 * @end_pos: (out) (allow-none): pointer to location where to store
917 * the end position, or %NULL
919 * Retrieves the position in bytes of the capturing parentheses named @name.
921 * If @name is a valid sub pattern name but it didn't match anything
922 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
923 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
925 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
926 * If the position cannot be fetched, @start_pos and @end_pos
927 * are left unchanged.
932 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
939 g_return_val_if_fail (match_info != NULL, FALSE);
940 g_return_val_if_fail (name != NULL, FALSE);
942 num = get_matched_substring_number (match_info, name);
946 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
950 * g_match_info_fetch_all:
951 * @match_info: a #GMatchInfo structure
953 * Bundles up pointers to each of the matching substrings from a match
954 * and stores them in an array of gchar pointers. The first element in
955 * the returned array is the match number 0, i.e. the entire matched
958 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
959 * "b" against "(a)?b") then an empty string is inserted.
961 * If the last match was obtained using the DFA algorithm, that is using
962 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
963 * strings are not that matched by sets of parentheses but that of the
964 * matched substring. Substrings are matched in reverse order of length,
965 * so the first one is the longest match.
967 * The strings are fetched from the string passed to the match function,
968 * so you cannot call this function after freeing the string.
970 * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
971 * It must be freed using g_strfreev(). If the previous match failed
977 g_match_info_fetch_all (const GMatchInfo *match_info)
979 /* we cannot use pcre_get_substring_list() because the returned value
980 * isn't suitable for g_strfreev(). */
984 g_return_val_if_fail (match_info != NULL, NULL);
986 if (match_info->matches < 0)
989 result = g_new (gchar *, match_info->matches + 1);
990 for (i = 0; i < match_info->matches; i++)
991 result[i] = g_match_info_fetch (match_info, i);
1001 g_regex_error_quark (void)
1003 static GQuark error_quark = 0;
1005 if (error_quark == 0)
1006 error_quark = g_quark_from_static_string ("g-regex-error-quark");
1015 * Increases reference count of @regex by 1.
1022 g_regex_ref (GRegex *regex)
1024 g_return_val_if_fail (regex != NULL, NULL);
1025 g_atomic_int_inc (®ex->ref_count);
1033 * Decreases reference count of @regex by 1. When reference count drops
1034 * to zero, it frees all the memory associated with the regex structure.
1039 g_regex_unref (GRegex *regex)
1041 g_return_if_fail (regex != NULL);
1043 if (g_atomic_int_exchange_and_add (®ex->ref_count, -1) - 1 == 0)
1045 g_free (regex->pattern);
1046 if (regex->pcre_re != NULL)
1047 pcre_free (regex->pcre_re);
1048 if (regex->extra != NULL)
1049 pcre_free (regex->extra);
1056 * @pattern: the regular expression
1057 * @compile_options: compile options for the regular expression, or 0
1058 * @match_options: match options for the regular expression, or 0
1059 * @error: return location for a #GError
1061 * Compiles the regular expression to an internal form, and does
1062 * the initial setup of the #GRegex structure.
1064 * Returns: a #GRegex structure. Call g_regex_unref() when you
1070 g_regex_new (const gchar *pattern,
1071 GRegexCompileFlags compile_options,
1072 GRegexMatchFlags match_options,
1077 const gchar *errmsg;
1080 gboolean optimize = FALSE;
1081 static gboolean initialized = FALSE;
1082 unsigned long int pcre_compile_options;
1084 g_return_val_if_fail (pattern != NULL, NULL);
1085 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1086 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1087 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1094 pcre_config (PCRE_CONFIG_UTF8, &support);
1097 msg = N_("PCRE library is compiled without UTF8 support");
1098 g_critical ("%s", msg);
1099 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1103 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
1106 msg = N_("PCRE library is compiled without UTF8 properties support");
1107 g_critical ("%s", msg);
1108 g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1115 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1116 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1117 if (compile_options & G_REGEX_OPTIMIZE)
1120 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1121 * instead uses UTF-8 only if required with PCRE_UTF8. */
1122 if (compile_options & G_REGEX_RAW)
1125 compile_options &= ~G_REGEX_RAW;
1130 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1131 match_options |= PCRE_NO_UTF8_CHECK;
1134 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1135 * not for the system one. */
1136 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1137 !(compile_options & G_REGEX_NEWLINE_LF))
1139 compile_options |= PCRE_NEWLINE_ANY;
1142 /* compile the pattern */
1143 re = pcre_compile2 (pattern, compile_options, &errcode,
1144 &errmsg, &erroffset, NULL);
1146 /* if the compilation failed, set the error member and return
1152 /* Translate the PCRE error code to GRegexError and use a translated
1153 * error message if possible */
1154 translate_compile_error (&errcode, &errmsg);
1156 /* PCRE uses byte offsets but we want to show character offsets */
1157 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1159 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1160 _("Error while compiling regular "
1161 "expression %s at char %d: %s"),
1162 pattern, erroffset, errmsg);
1163 g_propagate_error (error, tmp_error);
1168 /* For options set at the beginning of the pattern, pcre puts them into
1169 * compile options, e.g. "(?i)foo" will make the pcre structure store
1170 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1171 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1172 compile_options = pcre_compile_options;
1174 if (!(compile_options & G_REGEX_DUPNAMES))
1176 gboolean jchanged = FALSE;
1177 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1179 compile_options |= G_REGEX_DUPNAMES;
1182 regex = g_new0 (GRegex, 1);
1183 regex->ref_count = 1;
1184 regex->pattern = g_strdup (pattern);
1185 regex->pcre_re = re;
1186 regex->compile_opts = compile_options;
1187 regex->match_opts = match_options;
1191 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1194 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1195 G_REGEX_ERROR_OPTIMIZE,
1196 _("Error while optimizing "
1197 "regular expression %s: %s"),
1200 g_propagate_error (error, tmp_error);
1202 g_regex_unref (regex);
1211 * g_regex_get_pattern:
1212 * @regex: a #GRegex structure
1214 * Gets the pattern string associated with @regex, i.e. a copy of
1215 * the string passed to g_regex_new().
1217 * Returns: the pattern of @regex
1222 g_regex_get_pattern (const GRegex *regex)
1224 g_return_val_if_fail (regex != NULL, NULL);
1226 return regex->pattern;
1230 * g_regex_get_max_backref:
1233 * Returns the number of the highest back reference
1234 * in the pattern, or 0 if the pattern does not contain
1237 * Returns: the number of the highest back reference
1242 g_regex_get_max_backref (const GRegex *regex)
1246 pcre_fullinfo (regex->pcre_re, regex->extra,
1247 PCRE_INFO_BACKREFMAX, &value);
1253 * g_regex_get_capture_count:
1256 * Returns the number of capturing subpatterns in the pattern.
1258 * Returns: the number of capturing subpatterns
1263 g_regex_get_capture_count (const GRegex *regex)
1267 pcre_fullinfo (regex->pcre_re, regex->extra,
1268 PCRE_INFO_CAPTURECOUNT, &value);
1274 * g_regex_get_compile_flags:
1277 * Returns the compile options that @regex was created with.
1279 * Returns: flags from #GRegexCompileFlags
1284 g_regex_get_compile_flags (const GRegex *regex)
1286 g_return_val_if_fail (regex != NULL, 0);
1288 return regex->compile_opts;
1292 * g_regex_get_match_flags:
1295 * Returns the match options that @regex was created with.
1297 * Returns: flags from #GRegexMatchFlags
1302 g_regex_get_match_flags (const GRegex *regex)
1304 g_return_val_if_fail (regex != NULL, 0);
1306 return regex->match_opts;
1310 * g_regex_match_simple:
1311 * @pattern: the regular expression
1312 * @string: the string to scan for matches
1313 * @compile_options: compile options for the regular expression, or 0
1314 * @match_options: match options, or 0
1316 * Scans for a match in @string for @pattern.
1318 * This function is equivalent to g_regex_match() but it does not
1319 * require to compile the pattern with g_regex_new(), avoiding some
1320 * lines of code when you need just to do a match without extracting
1321 * substrings, capture counts, and so on.
1323 * If this function is to be called on the same @pattern more than
1324 * once, it's more efficient to compile the pattern once with
1325 * g_regex_new() and then use g_regex_match().
1327 * Returns: %TRUE if the string matched, %FALSE otherwise
1332 g_regex_match_simple (const gchar *pattern,
1333 const gchar *string,
1334 GRegexCompileFlags compile_options,
1335 GRegexMatchFlags match_options)
1340 regex = g_regex_new (pattern, compile_options, 0, NULL);
1343 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1344 g_regex_unref (regex);
1350 * @regex: a #GRegex structure from g_regex_new()
1351 * @string: the string to scan for matches
1352 * @match_options: match options
1353 * @match_info: (out) (allow-none): pointer to location where to store
1354 * the #GMatchInfo, or %NULL if you do not need it
1356 * Scans for a match in string for the pattern in @regex.
1357 * The @match_options are combined with the match options specified
1358 * when the @regex structure was created, letting you have more
1359 * flexibility in reusing #GRegex structures.
1361 * A #GMatchInfo structure, used to get information on the match,
1362 * is stored in @match_info if not %NULL. Note that if @match_info
1363 * is not %NULL then it is created even if the function returns %FALSE,
1364 * i.e. you must free it regardless if regular expression actually matched.
1366 * To retrieve all the non-overlapping matches of the pattern in
1367 * string you can use g_match_info_next().
1371 * print_uppercase_words (const gchar *string)
1373 * /* Print all uppercase-only words. */
1375 * GMatchInfo *match_info;
1377 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1378 * g_regex_match (regex, string, 0, &match_info);
1379 * while (g_match_info_matches (match_info))
1381 * gchar *word = g_match_info_fetch (match_info, 0);
1382 * g_print ("Found: %s\n", word);
1384 * g_match_info_next (match_info, NULL);
1386 * g_match_info_free (match_info);
1387 * g_regex_unref (regex);
1391 * @string is not copied and is used in #GMatchInfo internally. If
1392 * you use any #GMatchInfo method (except g_match_info_free()) after
1393 * freeing or modifying @string then the behaviour is undefined.
1395 * Returns: %TRUE is the string matched, %FALSE otherwise
1400 g_regex_match (const GRegex *regex,
1401 const gchar *string,
1402 GRegexMatchFlags match_options,
1403 GMatchInfo **match_info)
1405 return g_regex_match_full (regex, string, -1, 0, match_options,
1410 * g_regex_match_full:
1411 * @regex: a #GRegex structure from g_regex_new()
1412 * @string: (array length=string_len): the string to scan for matches
1413 * @string_len: the length of @string, or -1 if @string is nul-terminated
1414 * @start_position: starting index of the string to match
1415 * @match_options: match options
1416 * @match_info: (out) (allow-none): pointer to location where to store
1417 * the #GMatchInfo, or %NULL if you do not need it
1418 * @error: location to store the error occuring, or %NULL to ignore errors
1420 * Scans for a match in string for the pattern in @regex.
1421 * The @match_options are combined with the match options specified
1422 * when the @regex structure was created, letting you have more
1423 * flexibility in reusing #GRegex structures.
1425 * Setting @start_position differs from just passing over a shortened
1426 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1427 * that begins with any kind of lookbehind assertion, such as "\b".
1429 * A #GMatchInfo structure, used to get information on the match, is
1430 * stored in @match_info if not %NULL. Note that if @match_info is
1431 * not %NULL then it is created even if the function returns %FALSE,
1432 * i.e. you must free it regardless if regular expression actually
1435 * @string is not copied and is used in #GMatchInfo internally. If
1436 * you use any #GMatchInfo method (except g_match_info_free()) after
1437 * freeing or modifying @string then the behaviour is undefined.
1439 * To retrieve all the non-overlapping matches of the pattern in
1440 * string you can use g_match_info_next().
1444 * print_uppercase_words (const gchar *string)
1446 * /* Print all uppercase-only words. */
1448 * GMatchInfo *match_info;
1449 * GError *error = NULL;
1451 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1452 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1453 * while (g_match_info_matches (match_info))
1455 * gchar *word = g_match_info_fetch (match_info, 0);
1456 * g_print ("Found: %s\n", word);
1458 * g_match_info_next (match_info, &error);
1460 * g_match_info_free (match_info);
1461 * g_regex_unref (regex);
1462 * if (error != NULL)
1464 * g_printerr ("Error while matching: %s\n", error->message);
1465 * g_error_free (error);
1470 * Returns: %TRUE is the string matched, %FALSE otherwise
1475 g_regex_match_full (const GRegex *regex,
1476 const gchar *string,
1478 gint start_position,
1479 GRegexMatchFlags match_options,
1480 GMatchInfo **match_info,
1486 g_return_val_if_fail (regex != NULL, FALSE);
1487 g_return_val_if_fail (string != NULL, FALSE);
1488 g_return_val_if_fail (start_position >= 0, FALSE);
1489 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1490 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1492 info = match_info_new (regex, string, string_len, start_position,
1493 match_options, FALSE);
1494 match_ok = g_match_info_next (info, error);
1495 if (match_info != NULL)
1498 g_match_info_free (info);
1504 * g_regex_match_all:
1505 * @regex: a #GRegex structure from g_regex_new()
1506 * @string: the string to scan for matches
1507 * @match_options: match options
1508 * @match_info: (out) (allow-none): pointer to location where to store
1509 * the #GMatchInfo, or %NULL if you do not need it
1511 * Using the standard algorithm for regular expression matching only
1512 * the longest match in the string is retrieved. This function uses
1513 * a different algorithm so it can retrieve all the possible matches.
1514 * For more documentation see g_regex_match_all_full().
1516 * A #GMatchInfo structure, used to get information on the match, is
1517 * stored in @match_info if not %NULL. Note that if @match_info is
1518 * not %NULL then it is created even if the function returns %FALSE,
1519 * i.e. you must free it regardless if regular expression actually
1522 * @string is not copied and is used in #GMatchInfo internally. If
1523 * you use any #GMatchInfo method (except g_match_info_free()) after
1524 * freeing or modifying @string then the behaviour is undefined.
1526 * Returns: %TRUE is the string matched, %FALSE otherwise
1531 g_regex_match_all (const GRegex *regex,
1532 const gchar *string,
1533 GRegexMatchFlags match_options,
1534 GMatchInfo **match_info)
1536 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1541 * g_regex_match_all_full:
1542 * @regex: a #GRegex structure from g_regex_new()
1543 * @string: (array length=string_len): the string to scan for matches
1544 * @string_len: the length of @string, or -1 if @string is nul-terminated
1545 * @start_position: starting index of the string to match
1546 * @match_options: match options
1547 * @match_info: (out) (allow-none): pointer to location where to store
1548 * the #GMatchInfo, or %NULL if you do not need it
1549 * @error: location to store the error occuring, or %NULL to ignore errors
1551 * Using the standard algorithm for regular expression matching only
1552 * the longest match in the string is retrieved, it is not possibile
1553 * to obtain all the available matches. For instance matching
1554 * "<a> <b> <c>" against the pattern "<.*>"
1555 * you get "<a> <b> <c>".
1557 * This function uses a different algorithm (called DFA, i.e. deterministic
1558 * finite automaton), so it can retrieve all the possible matches, all
1559 * starting at the same point in the string. For instance matching
1560 * "<a> <b> <c>" against the pattern "<.*>"
1561 * you would obtain three matches: "<a> <b> <c>",
1562 * "<a> <b>" and "<a>".
1564 * The number of matched strings is retrieved using
1565 * g_match_info_get_match_count(). To obtain the matched strings and
1566 * their position you can use, respectively, g_match_info_fetch() and
1567 * g_match_info_fetch_pos(). Note that the strings are returned in
1568 * reverse order of length; that is, the longest matching string is
1571 * Note that the DFA algorithm is slower than the standard one and it
1572 * is not able to capture substrings, so backreferences do not work.
1574 * Setting @start_position differs from just passing over a shortened
1575 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1576 * that begins with any kind of lookbehind assertion, such as "\b".
1578 * A #GMatchInfo structure, used to get information on the match, is
1579 * stored in @match_info if not %NULL. Note that if @match_info is
1580 * not %NULL then it is created even if the function returns %FALSE,
1581 * i.e. you must free it regardless if regular expression actually
1584 * @string is not copied and is used in #GMatchInfo internally. If
1585 * you use any #GMatchInfo method (except g_match_info_free()) after
1586 * freeing or modifying @string then the behaviour is undefined.
1588 * Returns: %TRUE is the string matched, %FALSE otherwise
1593 g_regex_match_all_full (const GRegex *regex,
1594 const gchar *string,
1596 gint start_position,
1597 GRegexMatchFlags match_options,
1598 GMatchInfo **match_info,
1604 g_return_val_if_fail (regex != NULL, FALSE);
1605 g_return_val_if_fail (string != NULL, FALSE);
1606 g_return_val_if_fail (start_position >= 0, FALSE);
1607 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1608 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1610 info = match_info_new (regex, string, string_len, start_position,
1611 match_options, TRUE);
1617 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1618 info->string, info->string_len,
1620 regex->match_opts | match_options,
1621 info->offsets, info->n_offsets,
1622 info->workspace, info->n_workspace);
1623 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1625 /* info->workspace is too small. */
1626 info->n_workspace *= 2;
1627 info->workspace = g_realloc (info->workspace,
1628 info->n_workspace * sizeof (gint));
1631 else if (info->matches == 0)
1633 /* info->offsets is too small. */
1634 info->n_offsets *= 2;
1635 info->offsets = g_realloc (info->offsets,
1636 info->n_offsets * sizeof (gint));
1639 else if (IS_PCRE_ERROR (info->matches))
1641 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1642 _("Error while matching regular expression %s: %s"),
1643 regex->pattern, match_error (info->matches));
1647 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1650 if (match_info != NULL)
1653 g_match_info_free (info);
1655 return info->matches >= 0;
1659 * g_regex_get_string_number:
1660 * @regex: #GRegex structure
1661 * @name: name of the subexpression
1663 * Retrieves the number of the subexpression named @name.
1665 * Returns: The number of the subexpression or -1 if @name
1671 g_regex_get_string_number (const GRegex *regex,
1676 g_return_val_if_fail (regex != NULL, -1);
1677 g_return_val_if_fail (name != NULL, -1);
1679 num = pcre_get_stringnumber (regex->pcre_re, name);
1680 if (num == PCRE_ERROR_NOSUBSTRING)
1687 * g_regex_split_simple:
1688 * @pattern: the regular expression
1689 * @string: the string to scan for matches
1690 * @compile_options: compile options for the regular expression, or 0
1691 * @match_options: match options, or 0
1693 * Breaks the string on the pattern, and returns an array of
1694 * the tokens. If the pattern contains capturing parentheses,
1695 * then the text for each of the substrings will also be returned.
1696 * If the pattern does not match anywhere in the string, then the
1697 * whole string is returned as the first token.
1699 * This function is equivalent to g_regex_split() but it does
1700 * not require to compile the pattern with g_regex_new(), avoiding
1701 * some lines of code when you need just to do a split without
1702 * extracting substrings, capture counts, and so on.
1704 * If this function is to be called on the same @pattern more than
1705 * once, it's more efficient to compile the pattern once with
1706 * g_regex_new() and then use g_regex_split().
1708 * As a special case, the result of splitting the empty string ""
1709 * is an empty vector, not a vector containing a single string.
1710 * The reason for this special case is that being able to represent
1711 * a empty vector is typically more useful than consistent handling
1712 * of empty elements. If you do need to represent empty elements,
1713 * you'll need to check for the empty string before calling this
1716 * A pattern that can match empty strings splits @string into
1717 * separate characters wherever it matches the empty string between
1718 * characters. For example splitting "ab c" using as a separator
1719 * "\s*", you will get "a", "b" and "c".
1721 * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1726 g_regex_split_simple (const gchar *pattern,
1727 const gchar *string,
1728 GRegexCompileFlags compile_options,
1729 GRegexMatchFlags match_options)
1734 regex = g_regex_new (pattern, compile_options, 0, NULL);
1737 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1738 g_regex_unref (regex);
1744 * @regex: a #GRegex structure
1745 * @string: the string to split with the pattern
1746 * @match_options: match time option flags
1748 * Breaks the string on the pattern, and returns an array of the tokens.
1749 * If the pattern contains capturing parentheses, then the text for each
1750 * of the substrings will also be returned. If the pattern does not match
1751 * anywhere in the string, then the whole string is returned as the first
1754 * As a special case, the result of splitting the empty string "" is an
1755 * empty vector, not a vector containing a single string. The reason for
1756 * this special case is that being able to represent a empty vector is
1757 * typically more useful than consistent handling of empty elements. If
1758 * you do need to represent empty elements, you'll need to check for the
1759 * empty string before calling this function.
1761 * A pattern that can match empty strings splits @string into separate
1762 * characters wherever it matches the empty string between characters.
1763 * For example splitting "ab c" using as a separator "\s*", you will get
1766 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1771 g_regex_split (const GRegex *regex,
1772 const gchar *string,
1773 GRegexMatchFlags match_options)
1775 return g_regex_split_full (regex, string, -1, 0,
1776 match_options, 0, NULL);
1780 * g_regex_split_full:
1781 * @regex: a #GRegex structure
1782 * @string: (array length=string_len): the string to split with the pattern
1783 * @string_len: the length of @string, or -1 if @string is nul-terminated
1784 * @start_position: starting index of the string to match
1785 * @match_options: match time option flags
1786 * @max_tokens: the maximum number of tokens to split @string into.
1787 * If this is less than 1, the string is split completely
1788 * @error: return location for a #GError
1790 * Breaks the string on the pattern, and returns an array of the tokens.
1791 * If the pattern contains capturing parentheses, then the text for each
1792 * of the substrings will also be returned. If the pattern does not match
1793 * anywhere in the string, then the whole string is returned as the first
1796 * As a special case, the result of splitting the empty string "" is an
1797 * empty vector, not a vector containing a single string. The reason for
1798 * this special case is that being able to represent a empty vector is
1799 * typically more useful than consistent handling of empty elements. If
1800 * you do need to represent empty elements, you'll need to check for the
1801 * empty string before calling this function.
1803 * A pattern that can match empty strings splits @string into separate
1804 * characters wherever it matches the empty string between characters.
1805 * For example splitting "ab c" using as a separator "\s*", you will get
1808 * Setting @start_position differs from just passing over a shortened
1809 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1810 * that begins with any kind of lookbehind assertion, such as "\b".
1812 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1817 g_regex_split_full (const GRegex *regex,
1818 const gchar *string,
1820 gint start_position,
1821 GRegexMatchFlags match_options,
1825 GError *tmp_error = NULL;
1826 GMatchInfo *match_info;
1831 /* position of the last separator. */
1832 gint last_separator_end;
1833 /* was the last match 0 bytes long? */
1834 gboolean last_match_is_empty;
1835 /* the returned array of char **s */
1836 gchar **string_list;
1838 g_return_val_if_fail (regex != NULL, NULL);
1839 g_return_val_if_fail (string != NULL, NULL);
1840 g_return_val_if_fail (start_position >= 0, NULL);
1841 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1842 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1844 if (max_tokens <= 0)
1845 max_tokens = G_MAXINT;
1848 string_len = strlen (string);
1850 /* zero-length string */
1851 if (string_len - start_position == 0)
1852 return g_new0 (gchar *, 1);
1854 if (max_tokens == 1)
1856 string_list = g_new0 (gchar *, 2);
1857 string_list[0] = g_strndup (&string[start_position],
1858 string_len - start_position);
1864 last_separator_end = start_position;
1865 last_match_is_empty = FALSE;
1867 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1868 match_options, &match_info, &tmp_error);
1869 while (tmp_error == NULL)
1873 last_match_is_empty =
1874 (match_info->offsets[0] == match_info->offsets[1]);
1876 /* we need to skip empty separators at the same position of the end
1877 * of another separator. e.g. the string is "a b" and the separator
1878 * is " *", so from 1 to 2 we have a match and at position 2 we have
1879 * an empty match. */
1880 if (last_separator_end != match_info->offsets[1])
1885 token = g_strndup (string + last_separator_end,
1886 match_info->offsets[0] - last_separator_end);
1887 list = g_list_prepend (list, token);
1890 /* if there were substrings, these need to be added to
1892 match_count = g_match_info_get_match_count (match_info);
1893 if (match_count > 1)
1895 for (i = 1; i < match_count; i++)
1896 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1902 /* if there was no match, copy to end of string. */
1903 if (!last_match_is_empty)
1905 gchar *token = g_strndup (string + last_separator_end,
1906 match_info->string_len - last_separator_end);
1907 list = g_list_prepend (list, token);
1909 /* no more tokens, end the loop. */
1913 /* -1 to leave room for the last part. */
1914 if (token_count >= max_tokens - 1)
1916 /* we have reached the maximum number of tokens, so we copy
1917 * the remaining part of the string. */
1918 if (last_match_is_empty)
1920 /* the last match was empty, so we have moved one char
1921 * after the real position to avoid empty matches at the
1923 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1925 /* the if is needed in the case we have terminated the available
1926 * tokens, but we are at the end of the string, so there are no
1927 * characters left to copy. */
1928 if (string_len > match_info->pos)
1930 gchar *token = g_strndup (string + match_info->pos,
1931 string_len - match_info->pos);
1932 list = g_list_prepend (list, token);
1938 last_separator_end = match_info->pos;
1939 if (last_match_is_empty)
1940 /* if the last match was empty, g_match_info_next() has moved
1941 * forward to avoid infinite loops, but we still need to copy that
1943 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1945 match_ok = g_match_info_next (match_info, &tmp_error);
1947 g_match_info_free (match_info);
1948 if (tmp_error != NULL)
1950 g_propagate_error (error, tmp_error);
1951 g_list_foreach (list, (GFunc)g_free, NULL);
1953 match_info->pos = -1;
1957 string_list = g_new (gchar *, g_list_length (list) + 1);
1959 for (last = g_list_last (list); last; last = g_list_previous (last))
1960 string_list[i++] = last->data;
1961 string_list[i] = NULL;
1970 REPL_TYPE_CHARACTER,
1971 REPL_TYPE_SYMBOLIC_REFERENCE,
1972 REPL_TYPE_NUMERIC_REFERENCE,
1973 REPL_TYPE_CHANGE_CASE
1978 CHANGE_CASE_NONE = 1 << 0,
1979 CHANGE_CASE_UPPER = 1 << 1,
1980 CHANGE_CASE_LOWER = 1 << 2,
1981 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1982 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1983 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1984 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1985 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1988 struct _InterpolationData
1994 ChangeCase change_case;
1998 free_interpolation_data (InterpolationData *data)
2000 g_free (data->text);
2004 static const gchar *
2005 expand_escape (const gchar *replacement,
2007 InterpolationData *data,
2012 const gchar *error_detail;
2014 GError *tmp_error = NULL;
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;
2057 data->type = REPL_TYPE_CHARACTER;
2067 h = g_ascii_xdigit_value (*p);
2070 error_detail = _("hexadecimal digit or '}' expected");
2081 for (i = 0; i < 2; i++)
2083 h = g_ascii_xdigit_value (*p);
2086 error_detail = _("hexadecimal digit expected");
2093 data->type = REPL_TYPE_STRING;
2094 data->text = g_new0 (gchar, 8);
2095 g_unichar_to_utf8 (x, data->text);
2099 data->type = REPL_TYPE_CHANGE_CASE;
2100 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2104 data->type = REPL_TYPE_CHANGE_CASE;
2105 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2109 data->type = REPL_TYPE_CHANGE_CASE;
2110 data->change_case = CHANGE_CASE_LOWER;
2114 data->type = REPL_TYPE_CHANGE_CASE;
2115 data->change_case = CHANGE_CASE_UPPER;
2119 data->type = REPL_TYPE_CHANGE_CASE;
2120 data->change_case = CHANGE_CASE_NONE;
2126 error_detail = _("missing '<' in symbolic reference");
2135 error_detail = _("unfinished symbolic reference");
2142 error_detail = _("zero-length symbolic reference");
2145 if (g_ascii_isdigit (*q))
2150 h = g_ascii_digit_value (*q);
2153 error_detail = _("digit expected");
2162 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2169 if (!g_ascii_isalnum (*r))
2171 error_detail = _("illegal symbolic reference");
2178 data->text = g_strndup (q, p - q);
2179 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2184 /* if \0 is followed by a number is an octal number representing a
2185 * character, else it is a numeric reference. */
2186 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2189 p = g_utf8_next_char (p);
2202 for (i = 0; i < 3; i++)
2204 h = g_ascii_digit_value (*p);
2214 if (i == 2 && base == 10)
2220 if (base == 8 || i == 3)
2222 data->type = REPL_TYPE_STRING;
2223 data->text = g_new0 (gchar, 8);
2224 g_unichar_to_utf8 (x, data->text);
2228 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2233 error_detail = _("stray final '\\'");
2237 error_detail = _("unknown escape sequence");
2244 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2245 tmp_error = g_error_new (G_REGEX_ERROR,
2246 G_REGEX_ERROR_REPLACE,
2247 _("Error while parsing replacement "
2248 "text \"%s\" at char %lu: %s"),
2250 (gulong)(p - replacement),
2252 g_propagate_error (error, tmp_error);
2258 split_replacement (const gchar *replacement,
2262 InterpolationData *data;
2263 const gchar *p, *start;
2265 start = p = replacement;
2270 data = g_new0 (InterpolationData, 1);
2271 start = p = expand_escape (replacement, p, data, error);
2274 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2276 free_interpolation_data (data);
2280 list = g_list_prepend (list, data);
2285 if (*p == '\\' || *p == '\0')
2289 data = g_new0 (InterpolationData, 1);
2290 data->text = g_strndup (start, p - start);
2291 data->type = REPL_TYPE_STRING;
2292 list = g_list_prepend (list, data);
2298 return g_list_reverse (list);
2301 /* Change the case of c based on change_case. */
2302 #define CHANGE_CASE(c, change_case) \
2303 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2304 g_unichar_tolower (c) : \
2305 g_unichar_toupper (c))
2308 string_append (GString *string,
2310 ChangeCase *change_case)
2314 if (text[0] == '\0')
2317 if (*change_case == CHANGE_CASE_NONE)
2319 g_string_append (string, text);
2321 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2323 c = g_utf8_get_char (text);
2324 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2325 g_string_append (string, g_utf8_next_char (text));
2326 *change_case = CHANGE_CASE_NONE;
2330 while (*text != '\0')
2332 c = g_utf8_get_char (text);
2333 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2334 text = g_utf8_next_char (text);
2340 interpolate_replacement (const GMatchInfo *match_info,
2345 InterpolationData *idata;
2347 ChangeCase change_case = CHANGE_CASE_NONE;
2349 for (list = data; list; list = list->next)
2352 switch (idata->type)
2354 case REPL_TYPE_STRING:
2355 string_append (result, idata->text, &change_case);
2357 case REPL_TYPE_CHARACTER:
2358 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2359 if (change_case & CHANGE_CASE_SINGLE_MASK)
2360 change_case = CHANGE_CASE_NONE;
2362 case REPL_TYPE_NUMERIC_REFERENCE:
2363 match = g_match_info_fetch (match_info, idata->num);
2366 string_append (result, match, &change_case);
2370 case REPL_TYPE_SYMBOLIC_REFERENCE:
2371 match = g_match_info_fetch_named (match_info, idata->text);
2374 string_append (result, match, &change_case);
2378 case REPL_TYPE_CHANGE_CASE:
2379 change_case = idata->change_case;
2387 /* whether actual match_info is needed for replacement, i.e.
2388 * whether there are references
2391 interpolation_list_needs_match (GList *list)
2393 while (list != NULL)
2395 InterpolationData *data = list->data;
2397 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2398 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2411 * @regex: a #GRegex structure
2412 * @string: (array length=string_len): the string to perform matches against
2413 * @string_len: the length of @string, or -1 if @string is nul-terminated
2414 * @start_position: starting index of the string to match
2415 * @replacement: text to replace each match with
2416 * @match_options: options for the match
2417 * @error: location to store the error occuring, or %NULL to ignore errors
2419 * Replaces all occurrences of the pattern in @regex with the
2420 * replacement text. Backreferences of the form '\number' or
2421 * '\g<number>' in the replacement text are interpolated by the
2422 * number-th captured subexpression of the match, '\g<name>' refers
2423 * to the captured subexpression with the given name. '\0' refers to the
2424 * complete match, but '\0' followed by a number is the octal representation
2425 * of a character. To include a literal '\' in the replacement, write '\\'.
2426 * There are also escapes that changes the case of the following text:
2429 * <varlistentry><term>\l</term>
2431 * <para>Convert to lower case the next character</para>
2434 * <varlistentry><term>\u</term>
2436 * <para>Convert to upper case the next character</para>
2439 * <varlistentry><term>\L</term>
2441 * <para>Convert to lower case till \E</para>
2444 * <varlistentry><term>\U</term>
2446 * <para>Convert to upper case till \E</para>
2449 * <varlistentry><term>\E</term>
2451 * <para>End case modification</para>
2456 * If you do not need to use backreferences use g_regex_replace_literal().
2458 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2459 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2460 * you can use g_regex_replace_literal().
2462 * Setting @start_position differs from just passing over a shortened
2463 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2464 * begins with any kind of lookbehind assertion, such as "\b".
2466 * Returns: a newly allocated string containing the replacements
2471 g_regex_replace (const GRegex *regex,
2472 const gchar *string,
2474 gint start_position,
2475 const gchar *replacement,
2476 GRegexMatchFlags match_options,
2481 GError *tmp_error = NULL;
2483 g_return_val_if_fail (regex != NULL, NULL);
2484 g_return_val_if_fail (string != NULL, NULL);
2485 g_return_val_if_fail (start_position >= 0, NULL);
2486 g_return_val_if_fail (replacement != NULL, NULL);
2487 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2488 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2490 list = split_replacement (replacement, &tmp_error);
2491 if (tmp_error != NULL)
2493 g_propagate_error (error, tmp_error);
2497 result = g_regex_replace_eval (regex,
2498 string, string_len, start_position,
2500 interpolate_replacement,
2503 if (tmp_error != NULL)
2504 g_propagate_error (error, tmp_error);
2506 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2513 literal_replacement (const GMatchInfo *match_info,
2517 g_string_append (result, data);
2522 * g_regex_replace_literal:
2523 * @regex: a #GRegex structure
2524 * @string: (array length=string_len): the string to perform matches against
2525 * @string_len: the length of @string, or -1 if @string is nul-terminated
2526 * @start_position: starting index of the string to match
2527 * @replacement: text to replace each match with
2528 * @match_options: options for the match
2529 * @error: location to store the error occuring, or %NULL to ignore errors
2531 * Replaces all occurrences of the pattern in @regex with the
2532 * replacement text. @replacement is replaced literally, to
2533 * include backreferences use g_regex_replace().
2535 * Setting @start_position differs from just passing over a
2536 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2537 * case of a pattern that begins with any kind of lookbehind
2538 * assertion, such as "\b".
2540 * Returns: a newly allocated string containing the replacements
2545 g_regex_replace_literal (const GRegex *regex,
2546 const gchar *string,
2548 gint start_position,
2549 const gchar *replacement,
2550 GRegexMatchFlags match_options,
2553 g_return_val_if_fail (replacement != NULL, NULL);
2554 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2556 return g_regex_replace_eval (regex,
2557 string, string_len, start_position,
2559 literal_replacement,
2560 (gpointer)replacement,
2565 * g_regex_replace_eval:
2566 * @regex: a #GRegex structure from g_regex_new()
2567 * @string (array length=string_len): string to perform matches against
2568 * @string_len: the length of @string, or -1 if @string is nul-terminated
2569 * @start_position: starting index of the string to match
2570 * @match_options: options for the match
2571 * @eval: a function to call for each match
2572 * @user_data: user data to pass to the function
2573 * @error: location to store the error occuring, or %NULL to ignore errors
2575 * Replaces occurrences of the pattern in regex with the output of
2576 * @eval for that occurrence.
2578 * Setting @start_position differs from just passing over a shortened
2579 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2580 * that begins with any kind of lookbehind assertion, such as "\b".
2582 * The following example uses g_regex_replace_eval() to replace multiple
2586 * eval_cb (const GMatchInfo *info,
2593 * match = g_match_info_fetch (info, 0);
2594 * r = g_hash_table_lookup ((GHashTable *)data, match);
2595 * g_string_append (res, r);
2607 * h = g_hash_table_new (g_str_hash, g_str_equal);
2609 * g_hash_table_insert (h, "1", "ONE");
2610 * g_hash_table_insert (h, "2", "TWO");
2611 * g_hash_table_insert (h, "3", "THREE");
2612 * g_hash_table_insert (h, "4", "FOUR");
2614 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2615 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2616 * g_hash_table_destroy (h);
2621 * Returns: a newly allocated string containing the replacements
2626 g_regex_replace_eval (const GRegex *regex,
2627 const gchar *string,
2629 gint start_position,
2630 GRegexMatchFlags match_options,
2631 GRegexEvalCallback eval,
2635 GMatchInfo *match_info;
2638 gboolean done = FALSE;
2639 GError *tmp_error = NULL;
2641 g_return_val_if_fail (regex != NULL, NULL);
2642 g_return_val_if_fail (string != NULL, NULL);
2643 g_return_val_if_fail (start_position >= 0, NULL);
2644 g_return_val_if_fail (eval != NULL, NULL);
2645 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2648 string_len = strlen (string);
2650 result = g_string_sized_new (string_len);
2652 /* run down the string making matches. */
2653 g_regex_match_full (regex, string, string_len, start_position,
2654 match_options, &match_info, &tmp_error);
2655 while (!done && g_match_info_matches (match_info))
2657 g_string_append_len (result,
2659 match_info->offsets[0] - str_pos);
2660 done = (*eval) (match_info, result, user_data);
2661 str_pos = match_info->offsets[1];
2662 g_match_info_next (match_info, &tmp_error);
2664 g_match_info_free (match_info);
2665 if (tmp_error != NULL)
2667 g_propagate_error (error, tmp_error);
2668 g_string_free (result, TRUE);
2672 g_string_append_len (result, string + str_pos, string_len - str_pos);
2673 return g_string_free (result, FALSE);
2677 * g_regex_check_replacement:
2678 * @replacement: the replacement string
2679 * @has_references: (out) (allow-none): location to store information about
2680 * references in @replacement or %NULL
2681 * @error: location to store error
2683 * Checks whether @replacement is a valid replacement string
2684 * (see g_regex_replace()), i.e. that all escape sequences in
2687 * If @has_references is not %NULL then @replacement is checked
2688 * for pattern references. For instance, replacement text 'foo\n'
2689 * does not contain references and may be evaluated without information
2690 * about actual match, but '\0\1' (whole match followed by first
2691 * subpattern) requires valid #GMatchInfo object.
2693 * Returns: whether @replacement is a valid replacement string
2698 g_regex_check_replacement (const gchar *replacement,
2699 gboolean *has_references,
2705 list = split_replacement (replacement, &tmp);
2709 g_propagate_error (error, tmp);
2714 *has_references = interpolation_list_needs_match (list);
2716 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2723 * g_regex_escape_string:
2724 * @string: (array length=length): the string to escape
2725 * @length: the length of @string, or -1 if @string is nul-terminated
2727 * Escapes the special characters used for regular expressions
2728 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2729 * function is useful to dynamically generate regular expressions.
2731 * @string can contain nul characters that are replaced with "\0",
2732 * in this case remember to specify the correct length of @string
2735 * Returns: a newly-allocated escaped string
2740 g_regex_escape_string (const gchar *string,
2744 const char *p, *piece_start, *end;
2746 g_return_val_if_fail (string != NULL, NULL);
2749 length = strlen (string);
2751 end = string + length;
2752 p = piece_start = string;
2753 escaped = g_string_sized_new (length + 1);
2774 if (p != piece_start)
2775 /* copy the previous piece. */
2776 g_string_append_len (escaped, piece_start, p - piece_start);
2777 g_string_append_c (escaped, '\\');
2779 g_string_append_c (escaped, '0');
2781 g_string_append_c (escaped, *p);
2785 p = g_utf8_next_char (p);
2790 if (piece_start < end)
2791 g_string_append_len (escaped, piece_start, end - piece_start);
2793 return g_string_free (escaped, FALSE);