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)
43 /* Mask of all the possible values for GRegexCompileFlags. */
44 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
49 G_REGEX_DOLLAR_ENDONLY | \
52 G_REGEX_NO_AUTO_CAPTURE | \
55 G_REGEX_NEWLINE_CR | \
56 G_REGEX_NEWLINE_LF | \
59 /* Mask of all the possible values for GRegexMatchFlags. */
60 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
61 G_REGEX_MATCH_NOTBOL | \
62 G_REGEX_MATCH_NOTEOL | \
63 G_REGEX_MATCH_NOTEMPTY | \
64 G_REGEX_MATCH_PARTIAL | \
65 G_REGEX_MATCH_NEWLINE_CR | \
66 G_REGEX_MATCH_NEWLINE_LF | \
67 G_REGEX_MATCH_NEWLINE_CRLF | \
68 G_REGEX_MATCH_NEWLINE_ANY)
70 /* if the string is in UTF-8 use g_utf8_ functions, else use
72 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
73 g_utf8_next_char (s) : \
75 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
76 g_utf8_prev_char (s) : \
81 GRegex *regex; /* the regex */
82 GRegexMatchFlags match_opts; /* options used at match time on the regex */
83 gint matches; /* number of matching sub patterns */
84 gint pos; /* position in the string where last match left off */
85 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
86 gint n_offsets; /* number of offsets */
87 gint *workspace; /* workspace for pcre_dfa_exec() */
88 gint n_workspace; /* number of workspace elements */
89 const gchar *string; /* string passed to the match function */
90 gssize string_len; /* length of string */
95 volatile gint ref_count; /* the ref count for the immutable part */
96 gchar *pattern; /* the pattern */
97 pcre *pcre_re; /* compiled form of the pattern */
98 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
99 GRegexMatchFlags match_opts; /* options used at match time on the regex */
100 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
103 /* TRUE if ret is an error code, FALSE otherwise. */
104 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
106 typedef struct _InterpolationData InterpolationData;
107 static gboolean interpolation_list_needs_match (GList *list);
108 static gboolean interpolate_replacement (const GMatchInfo *match_info,
111 static GList *split_replacement (const gchar *replacement,
113 static void free_interpolation_data (InterpolationData *data);
117 match_error (gint errcode)
121 case PCRE_ERROR_NOMATCH:
124 case PCRE_ERROR_NULL:
125 /* NULL argument, this should not happen in GRegex */
126 g_warning ("A NULL argument was passed to PCRE");
128 case PCRE_ERROR_BADOPTION:
129 return "bad options";
130 case PCRE_ERROR_BADMAGIC:
131 return _("corrupted object");
132 case PCRE_ERROR_UNKNOWN_OPCODE:
133 return N_("internal error or corrupted object");
134 case PCRE_ERROR_NOMEMORY:
135 return _("out of memory");
136 case PCRE_ERROR_NOSUBSTRING:
137 /* not used by pcre_exec() */
139 case PCRE_ERROR_MATCHLIMIT:
140 return _("backtracking limit reached");
141 case PCRE_ERROR_CALLOUT:
142 /* callouts are not implemented */
144 case PCRE_ERROR_BADUTF8:
145 case PCRE_ERROR_BADUTF8_OFFSET:
146 /* we do not check if strings are valid */
148 case PCRE_ERROR_PARTIAL:
151 case PCRE_ERROR_BADPARTIAL:
152 return _("the pattern contains items not supported for partial matching");
153 case PCRE_ERROR_INTERNAL:
154 return _("internal error");
155 case PCRE_ERROR_BADCOUNT:
156 /* negative ovecsize, this should not happen in GRegex */
157 g_warning ("A negative ovecsize was passed to PCRE");
159 case PCRE_ERROR_DFA_UITEM:
160 return _("the pattern contains items not supported for partial matching");
161 case PCRE_ERROR_DFA_UCOND:
162 return _("back references as conditions are not supported for partial matching");
163 case PCRE_ERROR_DFA_UMLIMIT:
164 /* the match_field field is not used in GRegex */
166 case PCRE_ERROR_DFA_WSSIZE:
167 /* handled expanding the workspace */
169 case PCRE_ERROR_DFA_RECURSE:
170 case PCRE_ERROR_RECURSIONLIMIT:
171 return _("recursion limit reached");
172 case PCRE_ERROR_NULLWSLIMIT:
173 return _("workspace limit for empty substrings reached");
174 case PCRE_ERROR_BADNEWLINE:
175 return _("invalid combination of newline flags");
179 return _("unknown error");
183 translate_compile_error (gint *errcode, gchar **errmsg)
185 /* Compile errors are created adding 100 to the error code returned
187 * If errcode is known we put the translatable error message in
188 * erromsg. If errcode is unknown we put the generic
189 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
190 * untranslated error message returned by PCRE.
191 * Note that there can be more PCRE errors with the same GRegexError
192 * and that some PCRE errors are useless for us.
198 case G_REGEX_ERROR_STRAY_BACKSLASH:
199 *errmsg = _("\\ at end of pattern");
201 case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
202 *errmsg = _("\\c at end of pattern");
204 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
205 *errmsg = _("unrecognized character follows \\");
208 /* A number of Perl escapes are not handled by PCRE.
209 * Therefore it explicitly raises ERR37.
211 *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
212 *errmsg = _("case-changing escapes (\\l, \\L, \\u, \\U) are not allowed here");
214 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
215 *errmsg = _("numbers out of order in {} quantifier");
217 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
218 *errmsg = _("number too big in {} quantifier");
220 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
221 *errmsg = _("missing terminating ] for character class");
223 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
224 *errmsg = _("invalid escape sequence in character class");
226 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
227 *errmsg = _("range out of order in character class");
229 case G_REGEX_ERROR_NOTHING_TO_REPEAT:
230 *errmsg = _("nothing to repeat");
232 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
233 *errmsg = _("unrecognized character after (?");
236 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
237 *errmsg = _("unrecognized character after (?<");
240 *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
241 *errmsg = _("unrecognized character after (?P");
243 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
244 *errmsg = _("POSIX named classes are supported only within a class");
246 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
247 *errmsg = _("missing terminating )");
250 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
251 *errmsg = _(") without opening (");
254 *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
255 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
256 * sequences here, '(?-54' would be an example for the second group.
258 *errmsg = _("(?R or (?[+-]digits must be followed by )");
260 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
261 *errmsg = _("reference to non-existent subpattern");
263 case G_REGEX_ERROR_UNTERMINATED_COMMENT:
264 *errmsg = _("missing ) after comment");
266 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
267 *errmsg = _("regular expression too large");
269 case G_REGEX_ERROR_MEMORY_ERROR:
270 *errmsg = _("failed to get memory");
272 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
273 *errmsg = _("lookbehind assertion is not fixed length");
275 case G_REGEX_ERROR_MALFORMED_CONDITION:
276 *errmsg = _("malformed number or name after (?(");
278 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
279 *errmsg = _("conditional group contains more than two branches");
281 case G_REGEX_ERROR_ASSERTION_EXPECTED:
282 *errmsg = _("assertion expected after (?(");
284 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
285 *errmsg = _("unknown POSIX class name");
287 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
288 *errmsg = _("POSIX collating elements are not supported");
290 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
291 *errmsg = _("character value in \\x{...} sequence is too large");
293 case G_REGEX_ERROR_INVALID_CONDITION:
294 *errmsg = _("invalid condition (?(0)");
296 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
297 *errmsg = _("\\C not allowed in lookbehind assertion");
299 case G_REGEX_ERROR_INFINITE_LOOP:
300 *errmsg = _("recursive call could loop indefinitely");
302 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
303 *errmsg = _("missing terminator in subpattern name");
305 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
306 *errmsg = _("two named subpatterns have the same name");
308 case G_REGEX_ERROR_MALFORMED_PROPERTY:
309 *errmsg = _("malformed \\P or \\p sequence");
311 case G_REGEX_ERROR_UNKNOWN_PROPERTY:
312 *errmsg = _("unknown property name after \\P or \\p");
314 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
315 *errmsg = _("subpattern name is too long (maximum 32 characters)");
317 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
318 *errmsg = _("too many named subpatterns (maximum 10,000)");
320 case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
321 *errmsg = _("octal value is greater than \\377");
323 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
324 *errmsg = _("DEFINE group contains more than one branch");
326 case G_REGEX_ERROR_DEFINE_REPETION:
327 *errmsg = _("repeating a DEFINE group is not allowed");
329 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
330 *errmsg = _("inconsistent NEWLINE options");
332 case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
333 *errmsg = _("\\g is not followed by a braced name or an optionally "
334 "braced non-zero number");
337 *errcode = G_REGEX_ERROR_INTERNAL;
338 *errmsg = _("unexpected repeat");
341 *errcode = G_REGEX_ERROR_INTERNAL;
342 *errmsg = _("code overflow");
345 *errcode = G_REGEX_ERROR_INTERNAL;
346 *errmsg = _("overran compiling workspace");
349 *errcode = G_REGEX_ERROR_INTERNAL;
350 *errmsg = _("previously-checked referenced subpattern not found");
353 /* This should not happen as we never pass a NULL erroffset */
354 g_warning ("erroffset passed as NULL");
355 *errcode = G_REGEX_ERROR_COMPILE;
358 /* This should not happen as we check options before passing them
359 * to pcre_compile2() */
360 g_warning ("unknown option bit(s) set");
361 *errcode = G_REGEX_ERROR_COMPILE;
366 /* These errors should not happen as we are using an UTF8-enabled PCRE
367 * and we do not check if strings are valid */
369 *errcode = G_REGEX_ERROR_COMPILE;
372 *errcode = G_REGEX_ERROR_COMPILE;
379 match_info_new (const GRegex *regex,
386 GMatchInfo *match_info;
389 string_len = strlen (string);
391 match_info = g_new0 (GMatchInfo, 1);
392 match_info->regex = g_regex_ref ((GRegex *)regex);
393 match_info->string = string;
394 match_info->string_len = string_len;
395 match_info->matches = PCRE_ERROR_NOMATCH;
396 match_info->pos = start_position;
397 match_info->match_opts = match_options;
401 /* These values should be enough for most cases, if they are not
402 * enough g_regex_match_all_full() will expand them. */
403 match_info->n_offsets = 24;
404 match_info->n_workspace = 100;
405 match_info->workspace = g_new (gint, match_info->n_workspace);
410 pcre_fullinfo (regex->pcre_re, regex->extra,
411 PCRE_INFO_CAPTURECOUNT, &capture_count);
412 match_info->n_offsets = (capture_count + 1) * 3;
414 match_info->offsets = g_new0 (gint, match_info->n_offsets);
420 * g_match_info_get_regex:
421 * @match_info: a #GMatchInfo
423 * Returns #GRegex object used in @match_info. It belongs to Glib
424 * and must not be freed. Use g_regex_ref() if you need to keep it
425 * after you free @match_info object.
427 * Returns: #GRegex object used in @match_info
432 g_match_info_get_regex (const GMatchInfo *match_info)
434 g_return_val_if_fail (match_info != NULL, NULL);
435 return match_info->regex;
439 * g_match_info_get_string:
440 * @match_info: a #GMatchInfo
442 * Returns the string searched with @match_info. This is the
443 * string passed to g_regex_match() or g_regex_replace() so
444 * you may not free it before calling this function.
446 * Returns: the string searched with @match_info
451 g_match_info_get_string (const GMatchInfo *match_info)
453 g_return_val_if_fail (match_info != NULL, NULL);
454 return match_info->string;
459 * @match_info: a #GMatchInfo
461 * Frees all the memory associated with the #GMatchInfo structure.
466 g_match_info_free (GMatchInfo *match_info)
470 g_regex_unref (match_info->regex);
471 g_free (match_info->offsets);
472 g_free (match_info->workspace);
479 * @match_info: a #GMatchInfo structure
480 * @error: location to store the error occuring, or %NULL to ignore errors
482 * Scans for the next match using the same parameters of the previous
483 * call to g_regex_match_full() or g_regex_match() that returned
486 * The match is done on the string passed to the match function, so you
487 * cannot free it before calling this function.
489 * Returns: %TRUE is the string matched, %FALSE otherwise
494 g_match_info_next (GMatchInfo *match_info,
499 g_return_val_if_fail (match_info != NULL, FALSE);
500 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
501 g_return_val_if_fail (match_info->pos >= 0, FALSE);
503 opts = match_info->regex->match_opts | match_info->match_opts;
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 |
511 match_info->match_opts,
513 match_info->n_offsets);
514 if (IS_PCRE_ERROR (match_info->matches))
516 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
517 _("Error while matching regular expression %s: %s"),
518 match_info->regex->pattern, match_error (match_info->matches));
522 /* avoid infinite loops if the pattern is an empty string or something
524 if (match_info->pos == match_info->offsets[1])
526 if (match_info->pos > match_info->string_len)
528 /* we have reached the end of the string */
529 match_info->pos = -1;
530 match_info->matches = PCRE_ERROR_NOMATCH;
534 match_info->pos = NEXT_CHAR (match_info->regex,
535 &match_info->string[match_info->pos]) -
540 match_info->pos = match_info->offsets[1];
543 return match_info->matches >= 0;
547 * g_match_info_matches:
548 * @match_info: a #GMatchInfo structure
550 * Returns whether the previous match operation succeeded.
552 * Returns: %TRUE if the previous match operation succeeded,
558 g_match_info_matches (const GMatchInfo *match_info)
560 g_return_val_if_fail (match_info != NULL, FALSE);
562 return match_info->matches >= 0;
566 * g_match_info_get_match_count:
567 * @match_info: a #GMatchInfo structure
569 * Retrieves the number of matched substrings (including substring 0,
570 * that is the whole matched text), so 1 is returned if the pattern
571 * has no substrings in it and 0 is returned if the match failed.
573 * If the last match was obtained using the DFA algorithm, that is
574 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
575 * count is not that of the number of capturing parentheses but that of
576 * the number of matched substrings.
578 * Returns: Number of matched substrings, or -1 if an error occurred
583 g_match_info_get_match_count (const GMatchInfo *match_info)
585 g_return_val_if_fail (match_info, -1);
587 if (match_info->matches == PCRE_ERROR_NOMATCH)
590 else if (match_info->matches < PCRE_ERROR_NOMATCH)
595 return match_info->matches;
599 * g_match_info_is_partial_match:
600 * @match_info: a #GMatchInfo structure
602 * Usually if the string passed to g_regex_match*() matches as far as
603 * it goes, but is too short to match the entire pattern, %FALSE is
604 * returned. There are circumstances where it might be helpful to
605 * distinguish this case from other cases in which there is no match.
607 * Consider, for example, an application where a human is required to
608 * type in data for a field with specific formatting requirements. An
609 * example might be a date in the form ddmmmyy, defined by the pattern
610 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
611 * If the application sees the user’s keystrokes one by one, and can
612 * check that what has been typed so far is potentially valid, it is
613 * able to raise an error as soon as a mistake is made.
615 * GRegex supports the concept of partial matching by means of the
616 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
617 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
618 * for a complete match, %FALSE otherwise. But, when these functions
619 * return %FALSE, you can check if the match was partial calling
620 * g_match_info_is_partial_match().
622 * When using partial matching you cannot use g_match_info_fetch*().
624 * Because of the way certain internal optimizations are implemented
625 * the partial matching algorithm cannot be used with all patterns.
626 * So repeated single characters such as "a{2,4}" and repeated single
627 * meta-sequences such as "\d+" are not permitted if the maximum number
628 * of occurrences is greater than one. Optional items such as "\d?"
629 * (where the maximum is one) are permitted. Quantifiers with any values
630 * are permitted after parentheses, so the invalid examples above can be
631 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
632 * for a pattern that does not conform to the restrictions, matching
633 * functions return an error.
635 * Returns: %TRUE if the match was partial, %FALSE otherwise
640 g_match_info_is_partial_match (const GMatchInfo *match_info)
642 g_return_val_if_fail (match_info != NULL, FALSE);
644 return match_info->matches == PCRE_ERROR_PARTIAL;
648 * g_match_info_expand_references:
649 * @match_info: a #GMatchInfo or %NULL
650 * @string_to_expand: the string to expand
651 * @error: location to store the error occuring, or %NULL to ignore errors
653 * Returns a new string containing the text in @string_to_expand with
654 * references and escape sequences expanded. References refer to the last
655 * match done with @string against @regex and have the same syntax used by
658 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
659 * passed to g_regex_new().
661 * The backreferences are extracted from the string passed to the match
662 * function, so you cannot call this function after freeing the string.
664 * @match_info may be %NULL in which case @string_to_expand must not
665 * contain references. For instance "foo\n" does not refer to an actual
666 * pattern and '\n' merely will be replaced with \n character,
667 * while to expand "\0" (whole match) one needs the result of a match.
668 * Use g_regex_check_replacement() to find out whether @string_to_expand
669 * contains references.
671 * Returns: the expanded string, or %NULL if an error occurred
676 g_match_info_expand_references (const GMatchInfo *match_info,
677 const gchar *string_to_expand,
682 GError *tmp_error = NULL;
684 g_return_val_if_fail (string_to_expand != NULL, NULL);
685 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
687 list = split_replacement (string_to_expand, &tmp_error);
688 if (tmp_error != NULL)
690 g_propagate_error (error, tmp_error);
694 if (!match_info && interpolation_list_needs_match (list))
696 g_critical ("String '%s' contains references to the match, can't "
697 "expand references without GMatchInfo object",
702 result = g_string_sized_new (strlen (string_to_expand));
703 interpolate_replacement (match_info, result, list);
705 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
708 return g_string_free (result, FALSE);
712 * g_match_info_fetch:
713 * @match_info: #GMatchInfo structure
714 * @match_num: number of the sub expression
716 * Retrieves the text matching the @match_num<!-- -->'th capturing
717 * parentheses. 0 is the full text of the match, 1 is the first paren
718 * set, 2 the second, and so on.
720 * If @match_num is a valid sub pattern but it didn't match anything
721 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
722 * string is returned.
724 * If the match was obtained using the DFA algorithm, that is using
725 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
726 * string is not that of a set of parentheses but that of a matched
727 * substring. Substrings are matched in reverse order of length, so
728 * 0 is the longest match.
730 * The string is fetched from the string passed to the match function,
731 * so you cannot call this function after freeing the string.
733 * Returns: The matched substring, or %NULL if an error occurred.
734 * You have to free the string yourself
739 g_match_info_fetch (const GMatchInfo *match_info,
742 /* we cannot use pcre_get_substring() because it allocates the
743 * string using pcre_malloc(). */
747 g_return_val_if_fail (match_info != NULL, NULL);
748 g_return_val_if_fail (match_num >= 0, NULL);
750 /* match_num does not exist or it didn't matched, i.e. matching "b"
751 * against "(a)?b" then group 0 is empty. */
752 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
754 else if (start == -1)
755 match = g_strdup ("");
757 match = g_strndup (&match_info->string[start], end - start);
763 * g_match_info_fetch_pos:
764 * @match_info: #GMatchInfo structure
765 * @match_num: number of the sub expression
766 * @start_pos: pointer to location where to store the start position
767 * @end_pos: pointer to location where to store the end position
769 * Retrieves the position of the @match_num<!-- -->'th capturing
770 * parentheses. 0 is the full text of the match, 1 is the first
771 * paren set, 2 the second, and so on.
773 * If @match_num is a valid sub pattern but it didn't match anything
774 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
775 * and @end_pos are set to -1 and %TRUE is returned.
777 * If the match was obtained using the DFA algorithm, that is using
778 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
779 * position is not that of a set of parentheses but that of a matched
780 * substring. Substrings are matched in reverse order of length, so
781 * 0 is the longest match.
783 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
784 * the position cannot be fetched, @start_pos and @end_pos are left
790 g_match_info_fetch_pos (const GMatchInfo *match_info,
795 g_return_val_if_fail (match_info != NULL, FALSE);
796 g_return_val_if_fail (match_num >= 0, FALSE);
798 /* make sure the sub expression number they're requesting is less than
799 * the total number of sub expressions that were matched. */
800 if (match_num >= match_info->matches)
803 if (start_pos != NULL)
804 *start_pos = match_info->offsets[2 * match_num];
807 *end_pos = match_info->offsets[2 * match_num + 1];
813 * Returns number of first matched subpattern with name @name.
814 * There may be more than one in case when DUPNAMES is used,
815 * and not all subpatterns with that name match;
816 * pcre_get_stringnumber() does not work in that case.
819 get_matched_substring_number (const GMatchInfo *match_info,
826 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
827 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
829 /* This code is copied from pcre_get.c: get_first_set() */
830 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
838 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
840 gint n = (entry[0] << 8) + entry[1];
841 if (match_info->offsets[n*2] >= 0)
845 return (first[0] << 8) + first[1];
849 * g_match_info_fetch_named:
850 * @match_info: #GMatchInfo structure
851 * @name: name of the subexpression
853 * Retrieves the text matching the capturing parentheses named @name.
855 * If @name is a valid sub pattern name but it didn't match anything
856 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
857 * then an empty string is returned.
859 * The string is fetched from the string passed to the match function,
860 * so you cannot call this function after freeing the string.
862 * Returns: The matched substring, or %NULL if an error occurred.
863 * You have to free the string yourself
868 g_match_info_fetch_named (const GMatchInfo *match_info,
871 /* we cannot use pcre_get_named_substring() because it allocates the
872 * string using pcre_malloc(). */
875 g_return_val_if_fail (match_info != NULL, NULL);
876 g_return_val_if_fail (name != NULL, NULL);
878 num = get_matched_substring_number (match_info, name);
882 return g_match_info_fetch (match_info, num);
886 * g_match_info_fetch_named_pos:
887 * @match_info: #GMatchInfo structure
888 * @name: name of the subexpression
889 * @start_pos: pointer to location where to store the start position
890 * @end_pos: pointer to location where to store the end position
892 * Retrieves the position of the capturing parentheses named @name.
894 * If @name is a valid sub pattern name but it didn't match anything
895 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
896 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
898 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
899 * the position cannot be fetched, @start_pos and @end_pos are left
905 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
912 g_return_val_if_fail (match_info != NULL, FALSE);
913 g_return_val_if_fail (name != NULL, FALSE);
915 num = get_matched_substring_number (match_info, name);
919 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
923 * g_match_info_fetch_all:
924 * @match_info: a #GMatchInfo structure
926 * Bundles up pointers to each of the matching substrings from a match
927 * and stores them in an array of gchar pointers. The first element in
928 * the returned array is the match number 0, i.e. the entire matched
931 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
932 * "b" against "(a)?b") then an empty string is inserted.
934 * If the last match was obtained using the DFA algorithm, that is using
935 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
936 * strings are not that matched by sets of parentheses but that of the
937 * matched substring. Substrings are matched in reverse order of length,
938 * so the first one is the longest match.
940 * The strings are fetched from the string passed to the match function,
941 * so you cannot call this function after freeing the string.
943 * Returns: a %NULL-terminated array of gchar * pointers. It must be
944 * freed using g_strfreev(). If the previous match failed %NULL is
950 g_match_info_fetch_all (const GMatchInfo *match_info)
952 /* we cannot use pcre_get_substring_list() because the returned value
953 * isn't suitable for g_strfreev(). */
957 g_return_val_if_fail (match_info != NULL, NULL);
959 if (match_info->matches < 0)
962 result = g_new (gchar *, match_info->matches + 1);
963 for (i = 0; i < match_info->matches; i++)
964 result[i] = g_match_info_fetch (match_info, i);
974 g_regex_error_quark (void)
976 static GQuark error_quark = 0;
978 if (error_quark == 0)
979 error_quark = g_quark_from_static_string ("g-regex-error-quark");
988 * Increases reference count of @regex by 1.
995 g_regex_ref (GRegex *regex)
997 g_return_val_if_fail (regex != NULL, NULL);
998 g_atomic_int_inc (®ex->ref_count);
1006 * Decreases reference count of @regex by 1. When reference count drops
1007 * to zero, it frees all the memory associated with the regex structure.
1012 g_regex_unref (GRegex *regex)
1014 g_return_if_fail (regex != NULL);
1016 if (g_atomic_int_exchange_and_add (®ex->ref_count, -1) - 1 == 0)
1018 g_free (regex->pattern);
1019 if (regex->pcre_re != NULL)
1020 pcre_free (regex->pcre_re);
1021 if (regex->extra != NULL)
1022 pcre_free (regex->extra);
1029 * @pattern: the regular expression
1030 * @compile_options: compile options for the regular expression
1031 * @match_options: match options for the regular expression
1032 * @error: return location for a #GError
1034 * Compiles the regular expression to an internal form, and does
1035 * the initial setup of the #GRegex structure.
1037 * Returns: a #GRegex structure. Call g_regex_unref() when you
1043 g_regex_new (const gchar *pattern,
1044 GRegexCompileFlags compile_options,
1045 GRegexMatchFlags match_options,
1053 gboolean optimize = FALSE;
1054 static gboolean initialized = FALSE;
1055 unsigned long int pcre_compile_options;
1057 g_return_val_if_fail (pattern != NULL, NULL);
1058 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1059 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1060 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1067 pcre_config (PCRE_CONFIG_UTF8, &support);
1070 msg = N_("PCRE library is compiled without UTF8 support");
1072 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1076 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
1079 msg = N_("PCRE library is compiled without UTF8 properties support");
1081 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1088 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1089 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1090 if (compile_options & G_REGEX_OPTIMIZE)
1093 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1094 * instead uses UTF-8 only if required with PCRE_UTF8. */
1095 if (compile_options & G_REGEX_RAW)
1098 compile_options &= ~G_REGEX_RAW;
1103 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1104 match_options |= PCRE_NO_UTF8_CHECK;
1107 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1108 * not for the system one. */
1109 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1110 !(compile_options & G_REGEX_NEWLINE_LF))
1112 compile_options |= PCRE_NEWLINE_ANY;
1115 /* compile the pattern */
1116 re = pcre_compile2 (pattern, compile_options, &errcode,
1117 (const gchar **)&errmsg, &erroffset, NULL);
1119 /* if the compilation failed, set the error member and return
1125 /* Translate the PCRE error code to GRegexError and use a translated
1126 * error message if possible */
1127 translate_compile_error (&errcode, &errmsg);
1129 /* PCRE uses byte offsets but we want to show character offsets */
1130 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1132 tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1133 _("Error while compiling regular "
1134 "expression %s at char %d: %s"),
1135 pattern, erroffset, errmsg);
1136 g_propagate_error (error, tmp_error);
1141 /* For options set at the beginning of the pattern, pcre puts them into
1142 * compile options, e.g. "(?i)foo" will make the pcre structure store
1143 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1144 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1145 compile_options = pcre_compile_options;
1147 if (!(compile_options & G_REGEX_DUPNAMES))
1149 gboolean jchanged = FALSE;
1150 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1152 compile_options |= G_REGEX_DUPNAMES;
1155 regex = g_new0 (GRegex, 1);
1156 regex->ref_count = 1;
1157 regex->pattern = g_strdup (pattern);
1158 regex->pcre_re = re;
1159 regex->compile_opts = compile_options;
1160 regex->match_opts = match_options;
1164 regex->extra = pcre_study (regex->pcre_re, 0, (const gchar **)&errmsg);
1167 GError *tmp_error = g_error_new (G_REGEX_ERROR,
1168 G_REGEX_ERROR_OPTIMIZE,
1169 _("Error while optimizing "
1170 "regular expression %s: %s"),
1173 g_propagate_error (error, tmp_error);
1182 * g_regex_get_pattern:
1183 * @regex: a #GRegex structure
1185 * Gets the pattern string associated with @regex, i.e. a copy of
1186 * the string passed to g_regex_new().
1188 * Returns: the pattern of @regex
1193 g_regex_get_pattern (const GRegex *regex)
1195 g_return_val_if_fail (regex != NULL, NULL);
1197 return regex->pattern;
1201 * g_regex_get_max_backref:
1204 * Returns the number of the highest back reference
1205 * in the pattern, or 0 if the pattern does not contain
1208 * Returns: the number of the highest back reference
1213 g_regex_get_max_backref (const GRegex *regex)
1217 pcre_fullinfo (regex->pcre_re, regex->extra,
1218 PCRE_INFO_BACKREFMAX, &value);
1224 * g_regex_get_capture_count:
1227 * Returns the number of capturing subpatterns in the pattern.
1229 * Returns: the number of capturing subpatterns
1234 g_regex_get_capture_count (const GRegex *regex)
1238 pcre_fullinfo (regex->pcre_re, regex->extra,
1239 PCRE_INFO_CAPTURECOUNT, &value);
1245 * g_regex_match_simple:
1246 * @pattern: the regular expression
1247 * @string: the string to scan for matches
1248 * @compile_options: compile options for the regular expression
1249 * @match_options: match options
1251 * Scans for a match in @string for @pattern.
1253 * This function is equivalent to g_regex_match() but it does not
1254 * require to compile the pattern with g_regex_new(), avoiding some
1255 * lines of code when you need just to do a match without extracting
1256 * substrings, capture counts, and so on.
1258 * If this function is to be called on the same @pattern more than
1259 * once, it's more efficient to compile the pattern once with
1260 * g_regex_new() and then use g_regex_match().
1262 * Returns: %TRUE is the string matched, %FALSE otherwise
1267 g_regex_match_simple (const gchar *pattern,
1268 const gchar *string,
1269 GRegexCompileFlags compile_options,
1270 GRegexMatchFlags match_options)
1275 regex = g_regex_new (pattern, compile_options, 0, NULL);
1278 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1279 g_regex_unref (regex);
1285 * @regex: a #GRegex structure from g_regex_new()
1286 * @string: the string to scan for matches
1287 * @match_options: match options
1288 * @match_info: pointer to location where to store the #GMatchInfo,
1289 * or %NULL if you do not need it
1291 * Scans for a match in string for the pattern in @regex.
1292 * The @match_options are combined with the match options specified
1293 * when the @regex structure was created, letting you have more
1294 * flexibility in reusing #GRegex structures.
1296 * A #GMatchInfo structure, used to get information on the match,
1297 * is stored in @match_info if not %NULL. Note that if @match_info
1298 * is not %NULL then it is created even if the function returns %FALSE,
1299 * i.e. you must free it regardless if regular expression actually matched.
1301 * To retrieve all the non-overlapping matches of the pattern in
1302 * string you can use g_match_info_next().
1306 * print_uppercase_words (const gchar *string)
1308 * /* Print all uppercase-only words. */
1310 * GMatchInfo *match_info;
1312 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1313 * g_regex_match (regex, string, 0, &match_info);
1314 * while (g_match_info_matches (match_info))
1316 * gchar *word = g_match_info_fetch (match_info, 0);
1317 * g_print ("Found: %s\n", word);
1319 * g_match_info_next (match_info, NULL);
1321 * g_match_info_free (match_info);
1322 * g_regex_unref (regex);
1326 * Returns: %TRUE is the string matched, %FALSE otherwise
1331 g_regex_match (const GRegex *regex,
1332 const gchar *string,
1333 GRegexMatchFlags match_options,
1334 GMatchInfo **match_info)
1336 return g_regex_match_full (regex, string, -1, 0, match_options,
1341 * g_regex_match_full:
1342 * @regex: a #GRegex structure from g_regex_new()
1343 * @string: the string to scan for matches
1344 * @string_len: the length of @string, or -1 if @string is nul-terminated
1345 * @start_position: starting index of the string to match
1346 * @match_options: match options
1347 * @match_info: pointer to location where to store the #GMatchInfo,
1348 * or %NULL if you do not need it
1349 * @error: location to store the error occuring, or %NULL to ignore errors
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 * Setting @start_position differs from just passing over a shortened
1357 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1358 * that begins with any kind of lookbehind assertion, such as "\b".
1360 * A #GMatchInfo structure, used to get information on the match, is
1361 * stored in @match_info if not %NULL. Note that if @match_info is
1362 * not %NULL then it is created even if the function returns %FALSE,
1363 * i.e. you must free it regardless if regular expression actually
1366 * @string is not copied and is used in #GMatchInfo internally. If
1367 * you use any #GMatchInfo method (except g_match_info_free()) after
1368 * freeing or modifying @string then the behaviour is undefined.
1370 * To retrieve all the non-overlapping matches of the pattern in
1371 * string you can use g_match_info_next().
1375 * print_uppercase_words (const gchar *string)
1377 * /* Print all uppercase-only words. */
1379 * GMatchInfo *match_info;
1380 * GError *error = NULL;
1382 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1383 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1384 * while (g_match_info_matches (match_info))
1386 * gchar *word = g_match_info_fetch (match_info, 0);
1387 * g_print ("Found: %s\n", word);
1389 * g_match_info_next (match_info, &error);
1391 * g_match_info_free (match_info);
1392 * g_regex_unref (regex);
1393 * if (error != NULL)
1395 * g_printerr ("Error while matching: %s\n", error->message);
1396 * g_error_free (error);
1401 * Returns: %TRUE is the string matched, %FALSE otherwise
1406 g_regex_match_full (const GRegex *regex,
1407 const gchar *string,
1409 gint start_position,
1410 GRegexMatchFlags match_options,
1411 GMatchInfo **match_info,
1417 g_return_val_if_fail (regex != NULL, FALSE);
1418 g_return_val_if_fail (string != NULL, FALSE);
1419 g_return_val_if_fail (start_position >= 0, FALSE);
1420 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1421 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1423 info = match_info_new (regex, string, string_len, start_position,
1424 match_options, FALSE);
1425 match_ok = g_match_info_next (info, error);
1426 if (match_info != NULL)
1429 g_match_info_free (info);
1435 * g_regex_match_all:
1436 * @regex: a #GRegex structure from g_regex_new()
1437 * @string: the string to scan for matches
1438 * @match_options: match options
1439 * @match_info: pointer to location where to store the #GMatchInfo,
1440 * or %NULL if you do not need it
1442 * Using the standard algorithm for regular expression matching only
1443 * the longest match in the string is retrieved. This function uses
1444 * a different algorithm so it can retrieve all the possible matches.
1445 * For more documentation see g_regex_match_all_full().
1447 * A #GMatchInfo structure, used to get information on the match, is
1448 * stored in @match_info if not %NULL. Note that if @match_info is
1449 * not %NULL then it is created even if the function returns %FALSE,
1450 * i.e. you must free it regardless if regular expression actually
1453 * Returns: %TRUE is the string matched, %FALSE otherwise
1458 g_regex_match_all (const GRegex *regex,
1459 const gchar *string,
1460 GRegexMatchFlags match_options,
1461 GMatchInfo **match_info)
1463 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1468 * g_regex_match_all_full:
1469 * @regex: a #GRegex structure from g_regex_new()
1470 * @string: the string to scan for matches
1471 * @string_len: the length of @string, or -1 if @string is nul-terminated
1472 * @start_position: starting index of the string to match
1473 * @match_options: match options
1474 * @match_info: pointer to location where to store the #GMatchInfo,
1475 * or %NULL if you do not need it
1476 * @error: location to store the error occuring, or %NULL to ignore errors
1478 * Using the standard algorithm for regular expression matching only
1479 * the longest match in the string is retrieved, it is not possibile
1480 * to obtain all the available matches. For instance matching
1481 * "<a> <b> <c>" against the pattern "<.*>"
1482 * you get "<a> <b> <c>".
1484 * This function uses a different algorithm (called DFA, i.e. deterministic
1485 * finite automaton), so it can retrieve all the possible matches, all
1486 * starting at the same point in the string. For instance matching
1487 * "<a> <b> <c>" against the pattern "<.*>"
1488 * you would obtain three matches: "<a> <b> <c>",
1489 * "<a> <b>" and "<a>".
1491 * The number of matched strings is retrieved using
1492 * g_match_info_get_match_count(). To obtain the matched strings and
1493 * their position you can use, respectively, g_match_info_fetch() and
1494 * g_match_info_fetch_pos(). Note that the strings are returned in
1495 * reverse order of length; that is, the longest matching string is
1498 * Note that the DFA algorithm is slower than the standard one and it
1499 * is not able to capture substrings, so backreferences do not work.
1501 * Setting @start_position differs from just passing over a shortened
1502 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1503 * that begins with any kind of lookbehind assertion, such as "\b".
1505 * A #GMatchInfo structure, used to get information on the match, is
1506 * stored in @match_info if not %NULL. Note that if @match_info is
1507 * not %NULL then it is created even if the function returns %FALSE,
1508 * i.e. you must free it regardless if regular expression actually
1511 * Returns: %TRUE is the string matched, %FALSE otherwise
1516 g_regex_match_all_full (const GRegex *regex,
1517 const gchar *string,
1519 gint start_position,
1520 GRegexMatchFlags match_options,
1521 GMatchInfo **match_info,
1527 g_return_val_if_fail (regex != NULL, FALSE);
1528 g_return_val_if_fail (string != NULL, FALSE);
1529 g_return_val_if_fail (start_position >= 0, FALSE);
1530 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1531 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1533 info = match_info_new (regex, string, string_len, start_position,
1534 match_options, TRUE);
1540 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1541 info->string, info->string_len,
1543 regex->match_opts | match_options,
1544 info->offsets, info->n_offsets,
1545 info->workspace, info->n_workspace);
1546 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1548 /* info->workspace is too small. */
1549 info->n_workspace *= 2;
1550 info->workspace = g_realloc (info->workspace,
1551 info->n_workspace * sizeof (gint));
1554 else if (info->matches == 0)
1556 /* info->offsets is too small. */
1557 info->n_offsets *= 2;
1558 info->offsets = g_realloc (info->offsets,
1559 info->n_offsets * sizeof (gint));
1562 else if (IS_PCRE_ERROR (info->matches))
1564 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1565 _("Error while matching regular expression %s: %s"),
1566 regex->pattern, match_error (info->matches));
1570 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1573 if (match_info != NULL)
1576 g_match_info_free (info);
1578 return info->matches >= 0;
1582 * g_regex_get_string_number:
1583 * @regex: #GRegex structure
1584 * @name: name of the subexpression
1586 * Retrieves the number of the subexpression named @name.
1588 * Returns: The number of the subexpression or -1 if @name
1594 g_regex_get_string_number (const GRegex *regex,
1599 g_return_val_if_fail (regex != NULL, -1);
1600 g_return_val_if_fail (name != NULL, -1);
1602 num = pcre_get_stringnumber (regex->pcre_re, name);
1603 if (num == PCRE_ERROR_NOSUBSTRING)
1610 * g_regex_split_simple:
1611 * @pattern: the regular expression
1612 * @string: the string to scan for matches
1613 * @compile_options: compile options for the regular expression
1614 * @match_options: match options
1616 * Breaks the string on the pattern, and returns an array of
1617 * the tokens. If the pattern contains capturing parentheses,
1618 * then the text for each of the substrings will also be returned.
1619 * If the pattern does not match anywhere in the string, then the
1620 * whole string is returned as the first token.
1622 * This function is equivalent to g_regex_split() but it does
1623 * not require to compile the pattern with g_regex_new(), avoiding
1624 * some lines of code when you need just to do a split without
1625 * extracting substrings, capture counts, and so on.
1627 * If this function is to be called on the same @pattern more than
1628 * once, it's more efficient to compile the pattern once with
1629 * g_regex_new() and then use g_regex_split().
1631 * As a special case, the result of splitting the empty string ""
1632 * is an empty vector, not a vector containing a single string.
1633 * The reason for this special case is that being able to represent
1634 * a empty vector is typically more useful than consistent handling
1635 * of empty elements. If you do need to represent empty elements,
1636 * you'll need to check for the empty string before calling this
1639 * A pattern that can match empty strings splits @string into
1640 * separate characters wherever it matches the empty string between
1641 * characters. For example splitting "ab c" using as a separator
1642 * "\s*", you will get "a", "b" and "c".
1644 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1649 g_regex_split_simple (const gchar *pattern,
1650 const gchar *string,
1651 GRegexCompileFlags compile_options,
1652 GRegexMatchFlags match_options)
1657 regex = g_regex_new (pattern, compile_options, 0, NULL);
1660 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1661 g_regex_unref (regex);
1667 * @regex: a #GRegex structure
1668 * @string: the string to split with the pattern
1669 * @match_options: match time option flags
1671 * Breaks the string on the pattern, and returns an array of the tokens.
1672 * If the pattern contains capturing parentheses, then the text for each
1673 * of the substrings will also be returned. If the pattern does not match
1674 * anywhere in the string, then the whole string is returned as the first
1677 * As a special case, the result of splitting the empty string "" is an
1678 * empty vector, not a vector containing a single string. The reason for
1679 * this special case is that being able to represent a empty vector is
1680 * typically more useful than consistent handling of empty elements. If
1681 * you do need to represent empty elements, you'll need to check for the
1682 * empty string before calling this function.
1684 * A pattern that can match empty strings splits @string into separate
1685 * characters wherever it matches the empty string between characters.
1686 * For example splitting "ab c" using as a separator "\s*", you will get
1689 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1694 g_regex_split (const GRegex *regex,
1695 const gchar *string,
1696 GRegexMatchFlags match_options)
1698 return g_regex_split_full (regex, string, -1, 0,
1699 match_options, 0, NULL);
1703 * g_regex_split_full:
1704 * @regex: a #GRegex structure
1705 * @string: the string to split with the pattern
1706 * @string_len: the length of @string, or -1 if @string is nul-terminated
1707 * @start_position: starting index of the string to match
1708 * @match_options: match time option flags
1709 * @max_tokens: the maximum number of tokens to split @string into.
1710 * If this is less than 1, the string is split completely
1711 * @error: return location for a #GError
1713 * Breaks the string on the pattern, and returns an array of the tokens.
1714 * If the pattern contains capturing parentheses, then the text for each
1715 * of the substrings will also be returned. If the pattern does not match
1716 * anywhere in the string, then the whole string is returned as the first
1719 * As a special case, the result of splitting the empty string "" is an
1720 * empty vector, not a vector containing a single string. The reason for
1721 * this special case is that being able to represent a empty vector is
1722 * typically more useful than consistent handling of empty elements. If
1723 * you do need to represent empty elements, you'll need to check for the
1724 * empty string before calling this function.
1726 * A pattern that can match empty strings splits @string into separate
1727 * characters wherever it matches the empty string between characters.
1728 * For example splitting "ab c" using as a separator "\s*", you will get
1731 * Setting @start_position differs from just passing over a shortened
1732 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1733 * that begins with any kind of lookbehind assertion, such as "\b".
1735 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1740 g_regex_split_full (const GRegex *regex,
1741 const gchar *string,
1743 gint start_position,
1744 GRegexMatchFlags match_options,
1748 GError *tmp_error = NULL;
1749 GMatchInfo *match_info;
1754 /* position of the last separator. */
1755 gint last_separator_end;
1756 /* was the last match 0 bytes long? */
1757 gboolean last_match_is_empty;
1758 /* the returned array of char **s */
1759 gchar **string_list;
1761 g_return_val_if_fail (regex != NULL, NULL);
1762 g_return_val_if_fail (string != NULL, NULL);
1763 g_return_val_if_fail (start_position >= 0, NULL);
1764 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1765 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1767 if (max_tokens <= 0)
1768 max_tokens = G_MAXINT;
1771 string_len = strlen (string);
1773 /* zero-length string */
1774 if (string_len - start_position == 0)
1775 return g_new0 (gchar *, 1);
1777 if (max_tokens == 1)
1779 string_list = g_new0 (gchar *, 2);
1780 string_list[0] = g_strndup (&string[start_position],
1781 string_len - start_position);
1787 last_separator_end = start_position;
1788 last_match_is_empty = FALSE;
1790 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1791 match_options, &match_info, &tmp_error);
1792 while (tmp_error == NULL)
1796 last_match_is_empty =
1797 (match_info->offsets[0] == match_info->offsets[1]);
1799 /* we need to skip empty separators at the same position of the end
1800 * of another separator. e.g. the string is "a b" and the separator
1801 * is " *", so from 1 to 2 we have a match and at position 2 we have
1802 * an empty match. */
1803 if (last_separator_end != match_info->offsets[1])
1808 token = g_strndup (string + last_separator_end,
1809 match_info->offsets[0] - last_separator_end);
1810 list = g_list_prepend (list, token);
1813 /* if there were substrings, these need to be added to
1815 match_count = g_match_info_get_match_count (match_info);
1816 if (match_count > 1)
1818 for (i = 1; i < match_count; i++)
1819 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1825 /* if there was no match, copy to end of string. */
1826 if (!last_match_is_empty)
1828 gchar *token = g_strndup (string + last_separator_end,
1829 match_info->string_len - last_separator_end);
1830 list = g_list_prepend (list, token);
1832 /* no more tokens, end the loop. */
1836 /* -1 to leave room for the last part. */
1837 if (token_count >= max_tokens - 1)
1839 /* we have reached the maximum number of tokens, so we copy
1840 * the remaining part of the string. */
1841 if (last_match_is_empty)
1843 /* the last match was empty, so we have moved one char
1844 * after the real position to avoid empty matches at the
1846 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1848 /* the if is needed in the case we have terminated the available
1849 * tokens, but we are at the end of the string, so there are no
1850 * characters left to copy. */
1851 if (string_len > match_info->pos)
1853 gchar *token = g_strndup (string + match_info->pos,
1854 string_len - match_info->pos);
1855 list = g_list_prepend (list, token);
1861 last_separator_end = match_info->pos;
1862 if (last_match_is_empty)
1863 /* if the last match was empty, g_match_info_next() has moved
1864 * forward to avoid infinite loops, but we still need to copy that
1866 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1868 match_ok = g_match_info_next (match_info, &tmp_error);
1870 g_match_info_free (match_info);
1871 if (tmp_error != NULL)
1873 g_propagate_error (error, tmp_error);
1874 g_list_foreach (list, (GFunc)g_free, NULL);
1876 match_info->pos = -1;
1880 string_list = g_new (gchar *, g_list_length (list) + 1);
1882 for (last = g_list_last (list); last; last = g_list_previous (last))
1883 string_list[i++] = last->data;
1884 string_list[i] = NULL;
1893 REPL_TYPE_CHARACTER,
1894 REPL_TYPE_SYMBOLIC_REFERENCE,
1895 REPL_TYPE_NUMERIC_REFERENCE,
1896 REPL_TYPE_CHANGE_CASE
1901 CHANGE_CASE_NONE = 1 << 0,
1902 CHANGE_CASE_UPPER = 1 << 1,
1903 CHANGE_CASE_LOWER = 1 << 2,
1904 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1905 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1906 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1907 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1908 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1911 struct _InterpolationData
1917 ChangeCase change_case;
1921 free_interpolation_data (InterpolationData *data)
1923 g_free (data->text);
1927 static const gchar *
1928 expand_escape (const gchar *replacement,
1930 InterpolationData *data,
1935 const gchar *error_detail;
1937 GError *tmp_error = NULL;
1945 data->type = REPL_TYPE_CHARACTER;
1950 data->type = REPL_TYPE_CHARACTER;
1955 data->type = REPL_TYPE_CHARACTER;
1960 data->type = REPL_TYPE_CHARACTER;
1965 data->type = REPL_TYPE_CHARACTER;
1970 data->type = REPL_TYPE_CHARACTER;
1975 data->type = REPL_TYPE_CHARACTER;
1980 data->type = REPL_TYPE_CHARACTER;
1990 h = g_ascii_xdigit_value (*p);
1993 error_detail = _("hexadecimal digit or '}' expected");
2004 for (i = 0; i < 2; i++)
2006 h = g_ascii_xdigit_value (*p);
2009 error_detail = _("hexadecimal digit expected");
2016 data->type = REPL_TYPE_STRING;
2017 data->text = g_new0 (gchar, 8);
2018 g_unichar_to_utf8 (x, data->text);
2022 data->type = REPL_TYPE_CHANGE_CASE;
2023 data->change_case = CHANGE_CASE_LOWER_SINGLE;
2027 data->type = REPL_TYPE_CHANGE_CASE;
2028 data->change_case = CHANGE_CASE_UPPER_SINGLE;
2032 data->type = REPL_TYPE_CHANGE_CASE;
2033 data->change_case = CHANGE_CASE_LOWER;
2037 data->type = REPL_TYPE_CHANGE_CASE;
2038 data->change_case = CHANGE_CASE_UPPER;
2042 data->type = REPL_TYPE_CHANGE_CASE;
2043 data->change_case = CHANGE_CASE_NONE;
2049 error_detail = _("missing '<' in symbolic reference");
2058 error_detail = _("unfinished symbolic reference");
2065 error_detail = _("zero-length symbolic reference");
2068 if (g_ascii_isdigit (*q))
2073 h = g_ascii_digit_value (*q);
2076 error_detail = _("digit expected");
2085 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2092 if (!g_ascii_isalnum (*r))
2094 error_detail = _("illegal symbolic reference");
2101 data->text = g_strndup (q, p - q);
2102 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2107 /* if \0 is followed by a number is an octal number representing a
2108 * character, else it is a numeric reference. */
2109 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2112 p = g_utf8_next_char (p);
2125 for (i = 0; i < 3; i++)
2127 h = g_ascii_digit_value (*p);
2137 if (i == 2 && base == 10)
2143 if (base == 8 || i == 3)
2145 data->type = REPL_TYPE_STRING;
2146 data->text = g_new0 (gchar, 8);
2147 g_unichar_to_utf8 (x, data->text);
2151 data->type = REPL_TYPE_NUMERIC_REFERENCE;
2156 error_detail = _("stray final '\\'");
2160 error_detail = _("unknown escape sequence");
2167 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2168 tmp_error = g_error_new (G_REGEX_ERROR,
2169 G_REGEX_ERROR_REPLACE,
2170 _("Error while parsing replacement "
2171 "text \"%s\" at char %lu: %s"),
2173 (gulong)(p - replacement),
2175 g_propagate_error (error, tmp_error);
2181 split_replacement (const gchar *replacement,
2185 InterpolationData *data;
2186 const gchar *p, *start;
2188 start = p = replacement;
2193 data = g_new0 (InterpolationData, 1);
2194 start = p = expand_escape (replacement, p, data, error);
2197 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2199 free_interpolation_data (data);
2203 list = g_list_prepend (list, data);
2208 if (*p == '\\' || *p == '\0')
2212 data = g_new0 (InterpolationData, 1);
2213 data->text = g_strndup (start, p - start);
2214 data->type = REPL_TYPE_STRING;
2215 list = g_list_prepend (list, data);
2221 return g_list_reverse (list);
2224 /* Change the case of c based on change_case. */
2225 #define CHANGE_CASE(c, change_case) \
2226 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2227 g_unichar_tolower (c) : \
2228 g_unichar_toupper (c))
2231 string_append (GString *string,
2233 ChangeCase *change_case)
2237 if (text[0] == '\0')
2240 if (*change_case == CHANGE_CASE_NONE)
2242 g_string_append (string, text);
2244 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2246 c = g_utf8_get_char (text);
2247 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2248 g_string_append (string, g_utf8_next_char (text));
2249 *change_case = CHANGE_CASE_NONE;
2253 while (*text != '\0')
2255 c = g_utf8_get_char (text);
2256 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2257 text = g_utf8_next_char (text);
2263 interpolate_replacement (const GMatchInfo *match_info,
2268 InterpolationData *idata;
2270 ChangeCase change_case = CHANGE_CASE_NONE;
2272 for (list = data; list; list = list->next)
2275 switch (idata->type)
2277 case REPL_TYPE_STRING:
2278 string_append (result, idata->text, &change_case);
2280 case REPL_TYPE_CHARACTER:
2281 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2282 if (change_case & CHANGE_CASE_SINGLE_MASK)
2283 change_case = CHANGE_CASE_NONE;
2285 case REPL_TYPE_NUMERIC_REFERENCE:
2286 match = g_match_info_fetch (match_info, idata->num);
2289 string_append (result, match, &change_case);
2293 case REPL_TYPE_SYMBOLIC_REFERENCE:
2294 match = g_match_info_fetch_named (match_info, idata->text);
2297 string_append (result, match, &change_case);
2301 case REPL_TYPE_CHANGE_CASE:
2302 change_case = idata->change_case;
2310 /* whether actual match_info is needed for replacement, i.e.
2311 * whether there are references
2314 interpolation_list_needs_match (GList *list)
2316 while (list != NULL)
2318 InterpolationData *data = list->data;
2320 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2321 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2334 * @regex: a #GRegex structure
2335 * @string: the string to perform matches against
2336 * @string_len: the length of @string, or -1 if @string is nul-terminated
2337 * @start_position: starting index of the string to match
2338 * @replacement: text to replace each match with
2339 * @match_options: options for the match
2340 * @error: location to store the error occuring, or %NULL to ignore errors
2342 * Replaces all occurances of the pattern in @regex with the
2343 * replacement text. Backreferences of the form '\number' or
2344 * '\g<number>' in the replacement text are interpolated by the
2345 * number-th captured subexpression of the match, '\g<name>' refers
2346 * to the captured subexpression with the given name. '\0' refers to the
2347 * complete match, but '\0' followed by a number is the octal representation
2348 * of a character. To include a literal '\' in the replacement, write '\\'.
2349 * There are also escapes that changes the case of the following text:
2352 * <varlistentry><term>\l</term>
2354 * <para>Convert to lower case the next character</para>
2357 * <varlistentry><term>\u</term>
2359 * <para>Convert to upper case the next character</para>
2362 * <varlistentry><term>\L</term>
2364 * <para>Convert to lower case till \E</para>
2367 * <varlistentry><term>\U</term>
2369 * <para>Convert to upper case till \E</para>
2372 * <varlistentry><term>\E</term>
2374 * <para>End case modification</para>
2379 * If you do not need to use backreferences use g_regex_replace_literal().
2381 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2382 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2383 * you can use g_regex_replace_literal().
2385 * Setting @start_position differs from just passing over a shortened
2386 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2387 * begins with any kind of lookbehind assertion, such as "\b".
2389 * Returns: a newly allocated string containing the replacements
2394 g_regex_replace (const GRegex *regex,
2395 const gchar *string,
2397 gint start_position,
2398 const gchar *replacement,
2399 GRegexMatchFlags match_options,
2404 GError *tmp_error = NULL;
2406 g_return_val_if_fail (regex != NULL, NULL);
2407 g_return_val_if_fail (string != NULL, NULL);
2408 g_return_val_if_fail (start_position >= 0, NULL);
2409 g_return_val_if_fail (replacement != NULL, NULL);
2410 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2411 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2413 list = split_replacement (replacement, &tmp_error);
2414 if (tmp_error != NULL)
2416 g_propagate_error (error, tmp_error);
2420 result = g_regex_replace_eval (regex,
2421 string, string_len, start_position,
2423 interpolate_replacement,
2426 if (tmp_error != NULL)
2427 g_propagate_error (error, tmp_error);
2429 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2436 literal_replacement (const GMatchInfo *match_info,
2440 g_string_append (result, data);
2445 * g_regex_replace_literal:
2446 * @regex: a #GRegex structure
2447 * @string: the string to perform matches against
2448 * @string_len: the length of @string, or -1 if @string is nul-terminated
2449 * @start_position: starting index of the string to match
2450 * @replacement: text to replace each match with
2451 * @match_options: options for the match
2452 * @error: location to store the error occuring, or %NULL to ignore errors
2454 * Replaces all occurances of the pattern in @regex with the
2455 * replacement text. @replacement is replaced literally, to
2456 * include backreferences use g_regex_replace().
2458 * Setting @start_position differs from just passing over a
2459 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2460 * case of a pattern that begins with any kind of lookbehind
2461 * assertion, such as "\b".
2463 * Returns: a newly allocated string containing the replacements
2468 g_regex_replace_literal (const GRegex *regex,
2469 const gchar *string,
2471 gint start_position,
2472 const gchar *replacement,
2473 GRegexMatchFlags match_options,
2476 g_return_val_if_fail (replacement != NULL, NULL);
2477 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2479 return g_regex_replace_eval (regex,
2480 string, string_len, start_position,
2482 literal_replacement,
2483 (gpointer)replacement,
2488 * g_regex_replace_eval:
2489 * @regex: a #GRegex structure from g_regex_new()
2490 * @string: string to perform matches against
2491 * @string_len: the length of @string, or -1 if @string is nul-terminated
2492 * @start_position: starting index of the string to match
2493 * @match_options: options for the match
2494 * @eval: a function to call for each match
2495 * @user_data: user data to pass to the function
2496 * @error: location to store the error occuring, or %NULL to ignore errors
2498 * Replaces occurances of the pattern in regex with the output of
2499 * @eval for that occurance.
2501 * Setting @start_position differs from just passing over a shortened
2502 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2503 * that begins with any kind of lookbehind assertion, such as "\b".
2505 * Returns: a newly allocated string containing the replacements
2510 g_regex_replace_eval (const GRegex *regex,
2511 const gchar *string,
2513 gint start_position,
2514 GRegexMatchFlags match_options,
2515 GRegexEvalCallback eval,
2519 GMatchInfo *match_info;
2522 gboolean done = FALSE;
2523 GError *tmp_error = NULL;
2525 g_return_val_if_fail (regex != NULL, NULL);
2526 g_return_val_if_fail (string != NULL, NULL);
2527 g_return_val_if_fail (start_position >= 0, NULL);
2528 g_return_val_if_fail (eval != NULL, NULL);
2529 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2532 string_len = strlen (string);
2534 result = g_string_sized_new (string_len);
2536 /* run down the string making matches. */
2537 g_regex_match_full (regex, string, string_len, start_position,
2538 match_options, &match_info, &tmp_error);
2539 while (!done && g_match_info_matches (match_info))
2541 g_string_append_len (result,
2543 match_info->offsets[0] - str_pos);
2544 done = (*eval) (match_info, result, user_data);
2545 str_pos = match_info->offsets[1];
2546 g_match_info_next (match_info, &tmp_error);
2548 g_match_info_free (match_info);
2549 if (tmp_error != NULL)
2551 g_propagate_error (error, tmp_error);
2552 g_string_free (result, TRUE);
2556 g_string_append_len (result, string + str_pos, string_len - str_pos);
2557 return g_string_free (result, FALSE);
2561 * g_regex_check_replacement:
2562 * @replacement: the replacement string
2563 * @has_references: location to store information about
2564 * references in @replacement or %NULL
2565 * @error: location to store error
2567 * Checks whether @replacement is a valid replacement string
2568 * (see g_regex_replace()), i.e. that all escape sequences in
2571 * If @has_references is not %NULL then @replacement is checked
2572 * for pattern references. For instance, replacement text 'foo\n'
2573 * does not contain references and may be evaluated without information
2574 * about actual match, but '\0\1' (whole match followed by first
2575 * subpattern) requires valid #GMatchInfo object.
2577 * Returns: whether @replacement is a valid replacement string
2582 g_regex_check_replacement (const gchar *replacement,
2583 gboolean *has_references,
2589 list = split_replacement (replacement, &tmp);
2593 g_propagate_error (error, tmp);
2598 *has_references = interpolation_list_needs_match (list);
2600 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2607 * g_regex_escape_string:
2608 * @string: the string to escape
2609 * @length: the length of @string, or -1 if @string is nul-terminated
2611 * Escapes the special characters used for regular expressions
2612 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2613 * function is useful to dynamically generate regular expressions.
2615 * @string can contain nul characters that are replaced with "\0",
2616 * in this case remember to specify the correct length of @string
2619 * Returns: a newly-allocated escaped string
2624 g_regex_escape_string (const gchar *string,
2628 const char *p, *piece_start, *end;
2630 g_return_val_if_fail (string != NULL, NULL);
2633 length = strlen (string);
2635 end = string + length;
2636 p = piece_start = string;
2637 escaped = g_string_sized_new (length + 1);
2658 if (p != piece_start)
2659 /* copy the previous piece. */
2660 g_string_append_len (escaped, piece_start, p - piece_start);
2661 g_string_append_c (escaped, '\\');
2663 g_string_append_c (escaped, '0');
2665 g_string_append_c (escaped, *p);
2669 p = g_utf8_next_char (p);
2674 if (piece_start < end)
2675 g_string_append_len (escaped, piece_start, end - piece_start);
2677 return g_string_free (escaped, FALSE);
2680 #define __G_REGEX_C__
2681 #include "galiasdef.c"