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
29 #include <glib/gi18n.h>
32 #ifdef USE_SYSTEM_PCRE
35 #include "pcre/pcre.h"
40 /* Mask of all the possible values for GRegexCompileFlags. */
41 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
46 G_REGEX_DOLLAR_ENDONLY | \
49 G_REGEX_NO_AUTO_CAPTURE | \
51 G_REGEX_NEWLINE_CR | \
52 G_REGEX_NEWLINE_LF | \
55 /* Mask of all the possible values for GRegexMatchFlags. */
56 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
57 G_REGEX_MATCH_NOTBOL | \
58 G_REGEX_MATCH_NOTEOL | \
59 G_REGEX_MATCH_NOTEMPTY | \
60 G_REGEX_MATCH_PARTIAL | \
61 G_REGEX_MATCH_NEWLINE_CR | \
62 G_REGEX_MATCH_NEWLINE_LF | \
63 G_REGEX_MATCH_NEWLINE_CRLF | \
64 G_REGEX_MATCH_NEWLINE_ANY)
66 /* if the string is in UTF-8 use g_utf8_ functions, else use
68 #define NEXT_CHAR(re, s) (((re)->pattern->compile_opts & PCRE_UTF8) ? \
69 g_utf8_next_char (s) : \
71 #define PREV_CHAR(re, s) (((re)->pattern->compile_opts & PCRE_UTF8) ? \
72 g_utf8_prev_char (s) : \
75 #define WORKSPACE_INITIAL 1000
76 #define OFFSETS_DFA_MIN_SIZE 21
78 /* atomically returns the pcre_extra struct in the regex. */
79 #define REGEX_GET_EXTRA(re) ((pcre_extra *)g_atomic_pointer_get (&(re)->pattern->extra))
81 /* this struct can be shared by more regexes */
84 volatile guint ref_count; /* the ref count for the immutable part */
85 gchar *pattern; /* the pattern */
86 pcre *pcre_re; /* compiled form of the pattern */
87 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
88 GRegexMatchFlags match_opts; /* options used at match time on the regex */
89 pcre_extra *extra; /* data stored when g_regex_optimize() is used */
92 /* this struct is used only by a single regex */
95 gint matches; /* number of matching sub patterns */
96 gint pos; /* position in the string where last match left off */
97 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
98 gint n_offsets; /* number of offsets */
99 gint *workspace; /* workspace for pcre_dfa_exec() */
100 gint n_workspace; /* number of workspace elements */
101 gssize string_len; /* length of the string last used against */
102 GSList *delims; /* delimiter sub strings from split next */
103 gint last_separator_end; /* position of the last separator for split_next_full() */
104 gboolean last_match_is_empty; /* was the last match in split_next_full() 0 bytes long? */
109 GRegexPattern *pattern; /* immutable part, shared */
110 GRegexMatch *match; /* mutable part, not shared */
113 /* TRUE if ret is an error code, FALSE otherwise. */
114 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
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 udes 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 g_regex_error_quark (void)
185 static GQuark error_quark = 0;
187 if (error_quark == 0)
188 error_quark = g_quark_from_static_string ("g-regex-error-quark");
193 static GRegexPattern *
194 regex_pattern_new (pcre *re,
195 const gchar *pattern,
196 GRegexCompileFlags compile_options,
197 GRegexMatchFlags match_options)
199 GRegexPattern *rp = g_new0 (GRegexPattern, 1);
202 rp->pattern = g_strdup (pattern);
203 rp->compile_opts = compile_options;
204 rp->match_opts = match_options;
208 static GRegexPattern *
209 regex_pattern_ref (GRegexPattern *rp)
211 /* increases the ref count of the immutable part of the GRegex */
212 g_atomic_int_inc ((gint*) &rp->ref_count);
217 regex_pattern_unref (GRegexPattern *rp)
219 /* decreases the ref count of the immutable part of the GRegex
220 * and deletes it if the ref count went to 0 */
221 if (g_atomic_int_exchange_and_add ((gint *) &rp->ref_count, -1) - 1 == 0)
223 g_free (rp->pattern);
224 if (rp->pcre_re != NULL)
225 pcre_free (rp->pcre_re);
226 if (rp->extra != NULL)
227 pcre_free (rp->extra);
233 regex_match_free (GRegexMatch *rm)
238 g_slist_foreach (rm->delims, (GFunc) g_free, NULL);
239 g_slist_free (rm->delims);
240 g_free (rm->offsets);
241 g_free (rm->workspace);
246 regex_lazy_init_match (GRegex *regex,
251 if (regex->match != NULL)
254 pcre_fullinfo (regex->pattern->pcre_re,
255 REGEX_GET_EXTRA (regex),
256 PCRE_INFO_CAPTURECOUNT, &n_offsets);
257 n_offsets = (MAX (n_offsets, min_offsets) + 1) * 3;
259 regex->match = g_new0 (GRegexMatch, 1);
260 regex->match->string_len = -1;
261 regex->match->matches = -1000;
262 regex->match->n_offsets = n_offsets;
263 regex->match->offsets = g_new0 (gint, n_offsets);
268 * @pattern: the regular expression.
269 * @compile_options: compile options for the regular expression.
270 * @match_options: match options for the regular expression.
271 * @error: return location for a #GError.
273 * Compiles the regular expression to an internal form, and does the initial
274 * setup of the #GRegex structure.
276 * Returns: a #GRegex structure.
281 g_regex_new (const gchar *pattern,
282 GRegexCompileFlags compile_options,
283 GRegexMatchFlags match_options,
289 static gboolean initialized = FALSE;
291 g_return_val_if_fail (pattern != NULL, NULL);
292 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
293 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
294 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
301 pcre_config (PCRE_CONFIG_UTF8, &support);
304 msg = N_("PCRE library is compiled without UTF8 support");
306 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
310 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
313 msg = N_("PCRE library is compiled without UTF8 properties support");
315 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
322 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
323 * instead uses UTF-8 only if required with PCRE_UTF8. */
324 if (compile_options & G_REGEX_RAW)
327 compile_options &= ~G_REGEX_RAW;
332 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
333 match_options |= PCRE_NO_UTF8_CHECK;
336 /* compile the pattern */
337 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
339 /* if the compilation failed, set the error member and return
343 GError *tmp_error = g_error_new (G_REGEX_ERROR,
344 G_REGEX_ERROR_COMPILE,
345 _("Error while compiling regular "
346 "expression %s at char %d: %s"),
347 pattern, erroffset, errmsg);
348 g_propagate_error (error, tmp_error);
354 GRegex *regex = g_new0 (GRegex, 1);
355 regex->pattern = regex_pattern_new (re, pattern,
356 compile_options, match_options);
365 * Frees all the memory associated with the regex structure.
370 g_regex_free (GRegex *regex)
375 regex_pattern_unref (regex->pattern);
376 regex_match_free (regex->match);
382 * @regex: a #GRegex structure from g_regex_new().
384 * Copies a #GRegex. The returned #Gregex is in the same state as after
385 * a call to g_regex_clear(), so it does not contain information on the
386 * last match. If @regex is %NULL it returns %NULL.
388 * The returned copy shares some of its internal state with the original
389 * @regex, and the other internal variables are created only when needed,
390 * so the copy is a lightweight operation.
392 * Returns: a newly allocated copy of @regex, or %NULL if an error
398 g_regex_copy (const GRegex *regex)
405 copy = g_new0 (GRegex, 1);
406 copy->pattern = regex_pattern_ref (regex->pattern);
412 * g_regex_get_pattern:
413 * @regex: a #GRegex structure.
415 * Gets the pattern string associated with @regex, i.e. a copy of the string passed
418 * Returns: the pattern of @regex.
423 g_regex_get_pattern (const GRegex *regex)
425 g_return_val_if_fail (regex != NULL, NULL);
427 return regex->pattern->pattern;
432 * @regex: a #GRegex structure.
434 * Clears out the members of @regex that are holding information about the
435 * last set of matches for this pattern. g_regex_clear() needs to be
436 * called between uses of g_regex_match_next() or g_regex_match_next_full()
437 * against new target strings.
442 g_regex_clear (GRegex *regex)
444 g_return_if_fail (regex != NULL);
446 if (regex->match == NULL)
449 regex->match->matches = -1000; /* an error code not used by PCRE */
450 regex->match->string_len = -1;
451 regex->match->pos = 0;
453 /* if the pattern was used with g_regex_split_next(), it may have
454 * delimiter offsets stored. Free up those guys as well. */
455 if (regex->match->delims != NULL)
457 g_slist_foreach (regex->match->delims, (GFunc) g_free, NULL);
458 g_slist_free (regex->match->delims);
459 regex->match->delims = NULL;
465 * @regex: a #GRegex structure.
466 * @error: return location for a #GError.
468 * If the pattern will be used many times, then it may be worth the
469 * effort to optimize it to improve the speed of matches.
471 * Returns: %TRUE if @regex has been optimized or was already optimized,
477 g_regex_optimize (GRegex *regex,
482 pcre_extra G_GNUC_MAY_ALIAS **extra_p;
484 g_return_val_if_fail (regex != NULL, FALSE);
485 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
487 if (REGEX_GET_EXTRA (regex) != NULL)
488 /* already optimized. */
491 extra = pcre_study (regex->pattern->pcre_re, 0, &errmsg);
495 GError *tmp_error = g_error_new (G_REGEX_ERROR,
496 G_REGEX_ERROR_OPTIMIZE,
497 _("Error while optimizing "
498 "regular expression %s: %s"),
499 regex->pattern->pattern,
501 g_propagate_error (error, tmp_error);
508 extra_p = ®ex->pattern->extra;
509 if (!g_atomic_pointer_compare_and_exchange ((gpointer *)extra_p, NULL, extra))
510 /* someone else has optimized the regex while this function was running */
517 * g_regex_match_simple:
518 * @pattern: the regular expression.
519 * @string: the string to scan for matches.
520 * @compile_options: compile options for the regular expression.
521 * @match_options: match options.
523 * Scans for a match in @string for @pattern.
525 * This function is equivalent to g_regex_match() but it does not
526 * require to compile the pattern with g_regex_new(), avoiding some
527 * lines of code when you need just to do a match without extracting
528 * substrings, capture counts, and so on.
530 * If this function is to be called on the same @pattern more than
531 * once, it's more efficient to compile the pattern once with
532 * g_regex_new() and then use g_regex_match().
534 * Returns: %TRUE is the string matched, %FALSE otherwise.
539 g_regex_match_simple (const gchar *pattern,
541 GRegexCompileFlags compile_options,
542 GRegexMatchFlags match_options)
547 regex = g_regex_new (pattern, compile_options, 0, NULL);
550 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL);
551 g_regex_free (regex);
557 * @regex: a #GRegex structure from g_regex_new().
558 * @string: the string to scan for matches.
559 * @match_options: match options.
561 * Scans for a match in string for the pattern in @regex. The @match_options
562 * are combined with the match options specified when the @regex structure
563 * was created, letting you have more flexibility in reusing #GRegex
566 * Returns: %TRUE is the string matched, %FALSE otherwise.
571 g_regex_match (GRegex *regex,
573 GRegexMatchFlags match_options)
575 return g_regex_match_full (regex, string, -1, 0,
576 match_options, NULL);
580 * g_regex_match_full:
581 * @regex: a #GRegex structure from g_regex_new().
582 * @string: the string to scan for matches.
583 * @string_len: the length of @string, or -1 if @string is nul-terminated.
584 * @start_position: starting index of the string to match.
585 * @match_options: match options.
586 * @error: location to store the error occuring, or NULL to ignore errors.
588 * Scans for a match in string for the pattern in @regex. The @match_options
589 * are combined with the match options specified when the @regex structure
590 * was created, letting you have more flexibility in reusing #GRegex
593 * Setting @start_position differs from just passing over a shortened string
594 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
595 * with any kind of lookbehind assertion, such as "\b".
597 * Returns: %TRUE is the string matched, %FALSE otherwise.
602 g_regex_match_full (GRegex *regex,
606 GRegexMatchFlags match_options,
609 g_return_val_if_fail (regex != NULL, FALSE);
610 g_return_val_if_fail (string != NULL, FALSE);
611 g_return_val_if_fail (start_position >= 0, FALSE);
612 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
613 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
615 regex_lazy_init_match (regex, 0);
618 string_len = strlen(string);
620 regex->match->string_len = string_len;
622 /* create regex->match->offsets if it does not exist */
623 regex_lazy_init_match (regex, 0);
625 /* perform the match */
626 regex->match->matches = pcre_exec (regex->pattern->pcre_re,
627 REGEX_GET_EXTRA (regex),
628 string, regex->match->string_len,
630 regex->pattern->match_opts | match_options,
631 regex->match->offsets, regex->match->n_offsets);
632 if (IS_PCRE_ERROR (regex->match->matches))
634 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
635 _("Error while matching regular expression %s: %s"),
636 regex->pattern->pattern, match_error (regex->match->matches));
640 /* set regex->match->pos to -1 so that a call to g_regex_match_next()
641 * fails without a previous call to g_regex_clear(). */
642 regex->match->pos = -1;
644 return regex->match->matches >= 0;
648 * g_regex_match_next:
649 * @regex: a #GRegex structure.
650 * @string: the string to scan for matches.
651 * @match_options: the match options.
653 * Scans for the next match in @string of the pattern in @regex.
654 * array. The match options are combined with the match options set when
655 * the @regex was created.
657 * You have to call g_regex_clear() to reuse the same pattern on a new
660 * Returns: %TRUE is the string matched, %FALSE otherwise.
665 g_regex_match_next (GRegex *regex,
667 GRegexMatchFlags match_options)
669 return g_regex_match_next_full (regex, string, -1, 0,
670 match_options, NULL);
674 * g_regex_match_next_full:
675 * @regex: a #GRegex structure.
676 * @string: the string to scan for matches.
677 * @string_len: the length of @string, or -1 if @string is nul-terminated.
678 * @start_position: starting index of the string to match.
679 * @match_options: the match options.
680 * @error: location to store the error occuring, or NULL to ignore errors.
682 * Scans for the next match in @string of the pattern in @regex. Calling
683 * g_regex_match_next_full() until it returns %FALSE, you can retrieve
684 * all the non-overlapping matches of the pattern in @string. Empty matches
685 * are included, so matching the string "ab" with the pattern "b*" will
686 * find three matches: "" at position 0, "b" from position 1 to 2 and
689 * The match options are combined with the match options set when the
690 * @regex was created.
692 * You have to call g_regex_clear() to reuse the same pattern on a new
695 * Setting @start_position differs from just passing over a shortened string
696 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
697 * with any kind of lookbehind assertion, such as "\b".
699 * Returns: %TRUE is the string matched, %FALSE otherwise.
704 g_regex_match_next_full (GRegex *regex,
708 GRegexMatchFlags match_options,
711 g_return_val_if_fail (regex != NULL, FALSE);
712 g_return_val_if_fail (string != NULL, FALSE);
713 g_return_val_if_fail (start_position >= 0, FALSE);
714 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
715 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
717 regex_lazy_init_match (regex, 0);
719 if (G_UNLIKELY (regex->match->pos < 0))
721 const gchar *msg = _("g_regex_match_next_full: called without a "
722 "previous call to g_regex_clear()");
723 g_log (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, msg);
724 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH, msg);
728 /* if this regex hasn't been used on this string before, then we
729 * need to calculate the length of the string, and set pos to the
731 * Knowing if this regex has been used on this string is a bit of
732 * a challenge. For now, we require the user to call g_regex_clear()
733 * in between usages on a new string. Not perfect, but not such a
734 * bad solution either.
736 if (regex->match->string_len == -1)
739 string_len = strlen(string);
740 regex->match->string_len = string_len;
742 regex->match->pos = start_position;
745 /* create regex->match->offsets if it does not exist */
746 regex_lazy_init_match (regex, 0);
748 /* perform the match */
749 regex->match->matches = pcre_exec (regex->pattern->pcre_re,
750 REGEX_GET_EXTRA (regex),
751 string, regex->match->string_len,
753 regex->pattern->match_opts | match_options,
754 regex->match->offsets, regex->match->n_offsets);
755 if (IS_PCRE_ERROR (regex->match->matches))
757 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
758 _("Error while matching regular expression %s: %s"),
759 regex->pattern->pattern, match_error (regex->match->matches));
763 /* avoid infinite loops if regex is an empty string or something
765 if (regex->match->pos == regex->match->offsets[1])
767 if (regex->match->pos > regex->match->string_len)
769 /* we have reached the end of the string */
770 regex->match->pos = -1;
773 regex->match->pos = NEXT_CHAR (regex, &string[regex->match->pos]) - string;
777 regex->match->pos = regex->match->offsets[1];
780 return regex->match->matches >= 0;
785 * @regex: a #GRegex structure from g_regex_new().
786 * @string: the string to scan for matches.
787 * @match_options: match options.
789 * Using the standard algorithm for regular expression matching only the
790 * longest match in the string is retrieved. This function uses a
791 * different algorithm so it can retrieve all the possible matches.
792 * For more documentation see g_regex_match_all_full().
794 * Returns: %TRUE is the string matched, %FALSE otherwise.
799 g_regex_match_all (GRegex *regex,
801 GRegexMatchFlags match_options)
803 return g_regex_match_all_full (regex, string, -1, 0,
804 match_options, NULL);
808 * g_regex_match_all_full:
809 * @regex: a #GRegex structure from g_regex_new().
810 * @string: the string to scan for matches.
811 * @string_len: the length of @string, or -1 if @string is nul-terminated.
812 * @start_position: starting index of the string to match.
813 * @match_options: match options.
814 * @error: location to store the error occuring, or NULL to ignore errors.
816 * Using the standard algorithm for regular expression matching only the
817 * longest match in the string is retrieved, it is not possibile to obtain
818 * all the available matches. For instance matching
819 * "<a> <b> <c>" against the pattern "<.*>" you get
820 * "<a> <b> <c>".
822 * This function uses a different algorithm (called DFA, i.e. deterministic
823 * finite automaton), so it can retrieve all the possible matches, all
824 * starting at the same point in the string. For instance matching
825 * "<a> <b> <c>" against the pattern "<.*>" you
826 * would obtain three matches: "<a> <b> <c>",
827 * "<a> <b>" and "<a>".
829 * The number of matched strings is retrieved using
830 * g_regex_get_match_count().
831 * To obtain the matched strings and their position you can use,
832 * respectively, g_regex_fetch() and g_regex_fetch_pos(). Note that the
833 * strings are returned in reverse order of length; that is, the longest
834 * matching string is given first.
836 * Note that the DFA algorithm is slower than the standard one and it is not
837 * able to capture substrings, so backreferences do not work.
839 * Setting @start_position differs from just passing over a shortened string
840 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
841 * with any kind of lookbehind assertion, such as "\b".
843 * Returns: %TRUE is the string matched, %FALSE otherwise.
848 g_regex_match_all_full (GRegex *regex,
852 GRegexMatchFlags match_options,
855 g_return_val_if_fail (regex != NULL, FALSE);
856 g_return_val_if_fail (string != NULL, FALSE);
857 g_return_val_if_fail (start_position >= 0, FALSE);
858 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
859 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
861 regex_lazy_init_match (regex, 0);
864 string_len = strlen(string);
866 regex->match->string_len = string_len;
868 if (regex->match->workspace == NULL)
870 regex->match->n_workspace = WORKSPACE_INITIAL;
871 regex->match->workspace = g_new (gint, regex->match->n_workspace);
874 if (regex->match->n_offsets < OFFSETS_DFA_MIN_SIZE)
876 regex->match->n_offsets = OFFSETS_DFA_MIN_SIZE;
877 regex->match->offsets = g_realloc (regex->match->offsets,
878 regex->match->n_offsets * sizeof(gint));
881 /* perform the match */
882 regex->match->matches = pcre_dfa_exec (regex->pattern->pcre_re,
883 REGEX_GET_EXTRA (regex),
884 string, regex->match->string_len,
886 regex->pattern->match_opts | match_options,
887 regex->match->offsets, regex->match->n_offsets,
888 regex->match->workspace,
889 regex->match->n_workspace);
890 if (regex->match->matches == PCRE_ERROR_DFA_WSSIZE)
892 /* regex->match->workspace is too small. */
893 regex->match->n_workspace *= 2;
894 regex->match->workspace = g_realloc (regex->match->workspace,
895 regex->match->n_workspace * sizeof(gint));
896 return g_regex_match_all_full (regex, string, string_len,
897 start_position, match_options, error);
899 else if (regex->match->matches == 0)
901 /* regex->match->offsets is too small. */
902 regex->match->n_offsets *= 2;
903 regex->match->offsets = g_realloc (regex->match->offsets,
904 regex->match->n_offsets * sizeof(gint));
905 return g_regex_match_all_full (regex, string, string_len,
906 start_position, match_options, error);
908 else if (IS_PCRE_ERROR (regex->match->matches))
910 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
911 _("Error while matching regular expression %s: %s"),
912 regex->pattern->pattern, match_error (regex->match->matches));
916 /* set regex->match->pos to -1 so that a call to g_regex_match_next()
917 * fails without a previous call to g_regex_clear(). */
918 regex->match->pos = -1;
920 return regex->match->matches >= 0;
924 * g_regex_get_match_count:
925 * @regex: a #GRegex structure.
927 * Retrieves the number of matched substrings (including substring 0, that
928 * is the whole matched text) in the last call to g_regex_match*(), so 1
929 * is returned if the pattern has no substrings in it and 0 is returned if
932 * If the last match was obtained using the DFA algorithm, that is using
933 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
934 * count is not that of the number of capturing parentheses but that of
935 * the number of matched substrings.
937 * Returns: Number of matched substrings, or -1 if an error occurred.
942 g_regex_get_match_count (const GRegex *regex)
944 g_return_val_if_fail (regex != NULL, -1);
946 if (regex->match == NULL)
949 if (regex->match->matches == PCRE_ERROR_NOMATCH)
952 else if (regex->match->matches < PCRE_ERROR_NOMATCH)
957 return regex->match->matches;
961 * g_regex_is_partial_match:
962 * @regex: a #GRegex structure.
964 * Usually if the string passed to g_regex_match*() matches as far as
965 * it goes, but is too short to match the entire pattern, %FALSE is
966 * returned. There are circumstances where it might be helpful to
967 * distinguish this case from other cases in which there is no match.
969 * Consider, for example, an application where a human is required to
970 * type in data for a field with specific formatting requirements. An
971 * example might be a date in the form ddmmmyy, defined by the pattern
972 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
973 * If the application sees the user’s keystrokes one by one, and can
974 * check that what has been typed so far is potentially valid, it is
975 * able to raise an error as soon as a mistake is made.
977 * GRegex supports the concept of partial matching by means of the
978 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
979 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
980 * for a complete match, %FALSE otherwise. But, when this functions
981 * returns %FALSE, you can check if the match was partial calling
982 * g_regex_is_partial_match().
984 * When using partial matching you cannot use g_regex_fetch*().
986 * Because of the way certain internal optimizations are implemented the
987 * partial matching algorithm cannot be used with all patterns. So repeated
988 * single characters such as "a{2,4}" and repeated single metasequences such
989 * as "\d+" are not permitted if the maximum number of occurrences is
990 * greater than one. Optional items such as "\d?" (where the maximum is one)
991 * are permitted. Quantifiers with any values are permitted after
992 * parentheses, so the invalid examples above can be coded thus "(a){2,4}"
993 * and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set for a pattern that does
994 * not conform to the restrictions, matching functions return an error.
996 * Returns: %TRUE if the match was partial, %FALSE otherwise.
1001 g_regex_is_partial_match (const GRegex *regex)
1003 g_return_val_if_fail (regex != NULL, FALSE);
1005 if (regex->match == NULL)
1008 return regex->match->matches == PCRE_ERROR_PARTIAL;
1013 * @regex: #GRegex structure used in last match.
1014 * @match_num: number of the sub expression.
1015 * @string: the string on which the last match was made.
1017 * Retrieves the text matching the @match_num<!-- -->'th capturing parentheses.
1018 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
1021 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
1022 * sub pattern 1, matching "b" against "(a)?b") then an empty string is
1025 * If the last match was obtained using the DFA algorithm, that is using
1026 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1027 * string is not that of a set of parentheses but that of a matched
1028 * substring. Substrings are matched in reverse order of length, so 0 is
1029 * the longest match.
1031 * Returns: The matched substring, or %NULL if an error occurred.
1032 * You have to free the string yourself.
1037 g_regex_fetch (const GRegex *regex,
1039 const gchar *string)
1041 /* we cannot use pcre_get_substring() because it allocates the
1042 * string using pcre_malloc(). */
1043 gchar *match = NULL;
1046 g_return_val_if_fail (regex != NULL, NULL);
1047 g_return_val_if_fail (match_num >= 0, NULL);
1049 if (regex->match == NULL)
1052 if (regex->match->string_len < 0)
1055 /* match_num does not exist or it didn't matched, i.e. matching "b"
1056 * against "(a)?b" then group 0 is empty. */
1057 if (!g_regex_fetch_pos (regex, match_num, &start, &end))
1059 else if (start == -1)
1060 match = g_strdup ("");
1062 match = g_strndup (&string[start], end - start);
1068 * g_regex_fetch_pos:
1069 * @regex: #GRegex structure used in last match.
1070 * @match_num: number of the sub expression.
1071 * @start_pos: pointer to location where to store the start position.
1072 * @end_pos: pointer to location where to store the end position.
1074 * Retrieves the position of the @match_num<!-- -->'th capturing parentheses.
1075 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
1078 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
1079 * sub pattern 1, matching "b" against "(a)?b") then @start_pos and @end_pos
1080 * are set to -1 and %TRUE is returned.
1082 * If the last match was obtained using the DFA algorithm, that is using
1083 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1084 * position is not that of a set of parentheses but that of a matched
1085 * substring. Substrings are matched in reverse order of length, so 0 is
1086 * the longest match.
1088 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
1089 * position cannot be fetched, @start_pos and @end_pos are left
1095 g_regex_fetch_pos (const GRegex *regex,
1100 g_return_val_if_fail (regex != NULL, FALSE);
1101 g_return_val_if_fail (match_num >= 0, FALSE);
1103 if (regex->match == NULL)
1106 /* make sure the sub expression number they're requesting is less than
1107 * the total number of sub expressions that were matched. */
1108 if (match_num >= regex->match->matches)
1111 if (start_pos != NULL)
1113 *start_pos = regex->match->offsets[2 * match_num];
1116 if (end_pos != NULL)
1118 *end_pos = regex->match->offsets[2 * match_num + 1];
1125 * g_regex_fetch_named:
1126 * @regex: #GRegex structure used in last match.
1127 * @name: name of the subexpression.
1128 * @string: the string on which the last match was made.
1130 * Retrieves the text matching the capturing parentheses named @name.
1132 * If @name is a valid sub pattern name but it didn't match anything (e.g.
1133 * sub pattern "X", matching "b" against "(?P<X>a)?b") then an empty
1134 * string is returned.
1136 * Returns: The matched substring, or %NULL if an error occurred.
1137 * You have to free the string yourself.
1142 g_regex_fetch_named (const GRegex *regex,
1144 const gchar *string)
1146 /* we cannot use pcre_get_named_substring() because it allocates the
1147 * string using pcre_malloc(). */
1150 g_return_val_if_fail (regex != NULL, NULL);
1151 g_return_val_if_fail (string != NULL, NULL);
1152 g_return_val_if_fail (name != NULL, NULL);
1154 num = g_regex_get_string_number (regex, name);
1158 return g_regex_fetch (regex, num, string);
1162 * g_regex_fetch_named_pos:
1163 * @regex: #GRegex structure used in last match.
1164 * @name: name of the subexpression.
1165 * @start_pos: pointer to location where to store the start position.
1166 * @end_pos: pointer to location where to store the end position.
1168 * Retrieves the position of the capturing parentheses named @name.
1170 * If @name is a valid sub pattern name but it didn't match anything (e.g.
1171 * sub pattern "X", matching "b" against "(?P<X>a)?b") then @start_pos and
1172 * @end_pos are set to -1 and %TRUE is returned.
1174 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
1175 * position cannot be fetched, @start_pos and @end_pos are left
1181 g_regex_fetch_named_pos (const GRegex *regex,
1188 num = g_regex_get_string_number (regex, name);
1192 return g_regex_fetch_pos (regex, num, start_pos, end_pos);
1196 * g_regex_fetch_all:
1197 * @regex: a #GRegex structure.
1198 * @string: the string on which the last match was made.
1200 * Bundles up pointers to each of the matching substrings from a match
1201 * and stores them in an array of gchar pointers. The first element in
1202 * the returned array is the match number 0, i.e. the entire matched
1205 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1206 * "b" against "(a)?b") then an empty string is inserted.
1208 * If the last match was obtained using the DFA algorithm, that is using
1209 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1210 * strings are not that matched by sets of parentheses but that of the
1211 * matched substring. Substrings are matched in reverse order of length,
1212 * so the first one is the longest match.
1214 * Returns: a %NULL-terminated array of gchar * pointers. It must be freed
1215 * using g_strfreev(). If the memory can't be allocated, returns
1221 g_regex_fetch_all (const GRegex *regex,
1222 const gchar *string)
1224 /* we cannot use pcre_get_substring_list() because the returned value
1225 * isn't suitable for g_strfreev(). */
1229 g_return_val_if_fail (regex != NULL, FALSE);
1230 g_return_val_if_fail (string != NULL, FALSE);
1232 if (regex->match == NULL)
1235 if (regex->match->matches < 0)
1238 result = g_new (gchar *, regex->match->matches + 1);
1239 for (i = 0; i < regex->match->matches; i++)
1240 result[i] = g_regex_fetch (regex, i, string);
1247 * g_regex_get_string_number:
1248 * @regex: #GRegex structure.
1249 * @name: name of the subexpression.
1251 * Retrieves the number of the subexpression named @name.
1253 * Returns: The number of the subexpression or -1 if @name does not exists.
1258 g_regex_get_string_number (const GRegex *regex,
1263 g_return_val_if_fail (regex != NULL, -1);
1264 g_return_val_if_fail (name != NULL, -1);
1266 num = pcre_get_stringnumber (regex->pattern->pcre_re, name);
1267 if (num == PCRE_ERROR_NOSUBSTRING)
1274 * g_regex_split_simple:
1275 * @pattern: the regular expression.
1276 * @string: the string to scan for matches.
1277 * @compile_options: compile options for the regular expression.
1278 * @match_options: match options.
1280 * Breaks the string on the pattern, and returns an array of the tokens.
1281 * If the pattern contains capturing parentheses, then the text for each
1282 * of the substrings will also be returned. If the pattern does not match
1283 * anywhere in the string, then the whole string is returned as the first
1286 * This function is equivalent to g_regex_split() but it does not
1287 * require to compile the pattern with g_regex_new(), avoiding some
1288 * lines of code when you need just to do a split without extracting
1289 * substrings, capture counts, and so on.
1291 * If this function is to be called on the same @pattern more than
1292 * once, it's more efficient to compile the pattern once with
1293 * g_regex_new() and then use g_regex_split().
1295 * As a special case, the result of splitting the empty string "" is an
1296 * empty vector, not a vector containing a single string. The reason for
1297 * this special case is that being able to represent a empty vector is
1298 * typically more useful than consistent handling of empty elements. If
1299 * you do need to represent empty elements, you'll need to check for the
1300 * empty string before calling this function.
1302 * A pattern that can match empty strings splits @string into separate
1303 * characters wherever it matches the empty string between characters.
1304 * For example splitting "ab c" using as a separator "\s*", you will get
1307 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev().
1312 g_regex_split_simple (const gchar *pattern,
1313 const gchar *string,
1314 GRegexCompileFlags compile_options,
1315 GRegexMatchFlags match_options)
1320 regex = g_regex_new (pattern, compile_options, 0, NULL);
1323 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1324 g_regex_free (regex);
1330 * @regex: a #GRegex structure.
1331 * @string: the string to split with the pattern.
1332 * @match_options: match time option flags.
1334 * Breaks the string on the pattern, and returns an array of the tokens.
1335 * If the pattern contains capturing parentheses, then the text for each
1336 * of the substrings will also be returned. If the pattern does not match
1337 * anywhere in the string, then the whole string is returned as the first
1340 * As a special case, the result of splitting the empty string "" is an
1341 * empty vector, not a vector containing a single string. The reason for
1342 * this special case is that being able to represent a empty vector is
1343 * typically more useful than consistent handling of empty elements. If
1344 * you do need to represent empty elements, you'll need to check for the
1345 * empty string before calling this function.
1347 * A pattern that can match empty strings splits @string into separate
1348 * characters wherever it matches the empty string between characters.
1349 * For example splitting "ab c" using as a separator "\s*", you will get
1352 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev().
1357 g_regex_split (GRegex *regex,
1358 const gchar *string,
1359 GRegexMatchFlags match_options)
1361 return g_regex_split_full (regex, string, -1, 0,
1362 match_options, 0, NULL);
1366 * g_regex_split_full:
1367 * @regex: a #GRegex structure.
1368 * @string: the string to split with the pattern.
1369 * @string_len: the length of @string, or -1 if @string is nul-terminated.
1370 * @start_position: starting index of the string to match.
1371 * @match_options: match time option flags.
1372 * @max_tokens: the maximum number of tokens to split @string into. If this
1373 * is less than 1, the string is split completely.
1374 * @error: return location for a #GError.
1376 * Breaks the string on the pattern, and returns an array of the tokens.
1377 * If the pattern contains capturing parentheses, then the text for each
1378 * of the substrings will also be returned. If the pattern does not match
1379 * anywhere in the string, then the whole string is returned as the first
1382 * As a special case, the result of splitting the empty string "" is an
1383 * empty vector, not a vector containing a single string. The reason for
1384 * this special case is that being able to represent a empty vector is
1385 * typically more useful than consistent handling of empty elements. If
1386 * you do need to represent empty elements, you'll need to check for the
1387 * empty string before calling this function.
1389 * A pattern that can match empty strings splits @string into separate
1390 * characters wherever it matches the empty string between characters.
1391 * For example splitting "ab c" using as a separator "\s*", you will get
1394 * Setting @start_position differs from just passing over a shortened string
1395 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1396 * with any kind of lookbehind assertion, such as "\b".
1398 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev().
1403 g_regex_split_full (GRegex *regex,
1404 const gchar *string,
1406 gint start_position,
1407 GRegexMatchFlags match_options,
1411 gchar **string_list; /* The array of char **s worked on */
1415 GError *tmp_error = NULL;
1417 g_return_val_if_fail (regex != NULL, NULL);
1418 g_return_val_if_fail (string != NULL, NULL);
1419 g_return_val_if_fail (start_position >= 0, NULL);
1420 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1421 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1423 regex_lazy_init_match (regex, 0);
1425 if (max_tokens <= 0)
1426 max_tokens = G_MAXINT;
1429 string_len = strlen(string);
1431 if (string_len - start_position == 0)
1432 return g_new0 (gchar *, 1);
1434 /* clear out the regex for reuse, just in case */
1435 g_regex_clear (regex);
1443 /* -1 to leave room for the last part. */
1444 if (tokens >= max_tokens - 1)
1446 /* we have reached the maximum number of tokens, so we copy
1447 * the remaining part of the string. */
1448 if (regex->match->last_match_is_empty)
1450 /* the last match was empty, so we have moved one char
1451 * after the real position to avoid empty matches at the
1453 regex->match->pos = PREV_CHAR (regex, &string[regex->match->pos]) - string;
1455 /* the if is needed in the case we have terminated the available
1456 * tokens, but we are at the end of the string, so there are no
1457 * characters left to copy. */
1458 if (string_len > regex->match->pos)
1460 token = g_strndup (string + regex->match->pos,
1461 string_len - regex->match->pos);
1462 list = g_list_prepend (list, token);
1468 token = g_regex_split_next_full (regex, string, string_len, start_position,
1469 match_options, &tmp_error);
1470 if (tmp_error != NULL)
1472 g_propagate_error (error, tmp_error);
1473 g_list_foreach (list, (GFunc)g_free, NULL);
1475 regex->match->pos = -1;
1480 /* no more tokens. */
1484 list = g_list_prepend (list, token);
1487 string_list = g_new (gchar *, g_list_length (list) + 1);
1489 for (last = g_list_last (list); last; last = g_list_previous (last))
1490 string_list[pos++] = last->data;
1491 string_list[pos] = 0;
1493 regex->match->pos = -1;
1500 * g_regex_split_next:
1501 * @regex: a #GRegex structure from g_regex_new().
1502 * @string: the string to split on pattern.
1503 * @match_options: match time options for the regex.
1505 * g_regex_split_next() breaks the string on pattern, and returns the
1506 * tokens, one per call. If the pattern contains capturing parentheses,
1507 * then the text for each of the substrings will also be returned.
1508 * If the pattern does not match anywhere in the string, then the whole
1509 * string is returned as the first token.
1511 * A pattern that can match empty strings splits @string into separate
1512 * characters wherever it matches the empty string between characters.
1513 * For example splitting "ab c" using as a separator "\s*", you will get
1516 * You have to call g_regex_clear() to reuse the same pattern on a new
1519 * Returns: a gchar * to the next token of the string.
1524 g_regex_split_next (GRegex *regex,
1525 const gchar *string,
1526 GRegexMatchFlags match_options)
1528 return g_regex_split_next_full (regex, string, -1, 0, match_options,
1533 * g_regex_split_next_full:
1534 * @regex: a #GRegex structure from g_regex_new().
1535 * @string: the string to split on pattern.
1536 * @string_len: the length of @string, or -1 if @string is nul-terminated.
1537 * @start_position: starting index of the string to match.
1538 * @match_options: match time options for the regex.
1539 * @error: return location for a #GError.
1541 * g_regex_split_next_full() breaks the string on pattern, and returns
1542 * the tokens, one per call. If the pattern contains capturing parentheses,
1543 * then the text for each of the substrings will also be returned.
1544 * If the pattern does not match anywhere in the string, then the whole
1545 * string is returned as the first token.
1547 * A pattern that can match empty strings splits @string into separate
1548 * characters wherever it matches the empty string between characters.
1549 * For example splitting "ab c" using as a separator "\s*", you will get
1552 * You have to call g_regex_clear() to reuse the same pattern on a new
1555 * Setting @start_position differs from just passing over a shortened string
1556 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1557 * with any kind of lookbehind assertion, such as "\b".
1559 * Returns: a gchar * to the next token of the string.
1564 g_regex_split_next_full (GRegex *regex,
1565 const gchar *string,
1567 gint start_position,
1568 GRegexMatchFlags match_options,
1572 gchar *token = NULL;
1575 GError *tmp_error = NULL;
1577 g_return_val_if_fail (regex != NULL, NULL);
1578 g_return_val_if_fail (string != NULL, NULL);
1579 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1580 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1582 regex_lazy_init_match (regex, 0);
1584 new_pos = MAX (regex->match->pos, start_position);
1585 if (regex->match->last_match_is_empty)
1586 /* if the last match was empty, g_regex_match_next_full() has moved
1587 * forward to avoid infinite loops, but we still need to copy that
1589 new_pos = PREV_CHAR(regex, &string[new_pos]) - string;
1591 /* if there are delimiter substrings stored, return those one at a
1594 if (regex->match->delims != NULL)
1596 token = regex->match->delims->data;
1597 regex->match->delims = g_slist_remove (regex->match->delims, token);
1601 if (regex->match->pos == -1)
1602 /* the last call to g_regex_match_next_full() returned NULL. */
1605 if (regex->match->string_len < 0)
1607 regex->match->last_match_is_empty = FALSE;
1608 /* initialize last_separator_end to start_position to skip the
1609 * empty token at the beginning of the string. */
1610 regex->match->last_separator_end = start_position;
1613 /* use g_regex_match_next() to find the next occurance of the pattern
1614 * in the string. We use new_pos to keep track of where the stuff
1615 * up to the current match starts. Copy that token of the string off
1616 * and append it to the buffer using g_strndup. */
1617 match_ok = g_regex_match_next_full (regex, string, string_len,
1618 start_position, match_options,
1620 if (tmp_error != NULL)
1622 g_propagate_error (error, tmp_error);
1628 regex->match->last_match_is_empty =
1629 (regex->match->offsets[0] == regex->match->offsets[1]);
1631 /* we need to skip empty separators at the same position of the end
1632 * of another separator. e.g. the string is "a b" and the separator
1633 * is "*", so from 1 to 2 we have a match and at position 2 we have
1634 * an empty match. */
1635 if (regex->match->last_separator_end != regex->match->offsets[1])
1637 token = g_strndup (string + new_pos, regex->match->offsets[0] - new_pos);
1639 /* if there were substrings, these need to get added to the
1641 match_count = g_regex_get_match_count (regex);
1642 if (match_count > 1)
1645 for (i = 1; i < match_count; i++)
1646 regex->match->delims = g_slist_append (regex->match->delims,
1647 g_regex_fetch (regex, i, string));
1650 regex->match->last_separator_end = regex->match->offsets[1];
1654 /* we have skipped an empty separator so we need to find the
1656 return g_regex_split_next_full (regex, string, string_len,
1657 start_position, match_options,
1663 /* if there was no match, copy to end of string. */
1664 if (!regex->match->last_match_is_empty)
1665 token = g_strndup (string + new_pos, regex->match->string_len - new_pos);
1676 REPL_TYPE_CHARACTER,
1677 REPL_TYPE_SYMBOLIC_REFERENCE,
1678 REPL_TYPE_NUMERIC_REFERENCE,
1679 REPL_TYPE_CHANGE_CASE
1684 CHANGE_CASE_NONE = 1 << 0,
1685 CHANGE_CASE_UPPER = 1 << 1,
1686 CHANGE_CASE_LOWER = 1 << 2,
1687 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1688 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1689 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1690 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1691 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1700 ChangeCase change_case;
1701 } InterpolationData;
1704 free_interpolation_data (InterpolationData *data)
1706 g_free (data->text);
1710 static const gchar *
1711 expand_escape (const gchar *replacement,
1713 InterpolationData *data,
1718 const gchar *error_detail;
1720 GError *tmp_error = NULL;
1728 data->type = REPL_TYPE_CHARACTER;
1733 data->type = REPL_TYPE_CHARACTER;
1738 data->type = REPL_TYPE_CHARACTER;
1743 data->type = REPL_TYPE_CHARACTER;
1748 data->type = REPL_TYPE_CHARACTER;
1753 data->type = REPL_TYPE_CHARACTER;
1758 data->type = REPL_TYPE_CHARACTER;
1763 data->type = REPL_TYPE_CHARACTER;
1773 h = g_ascii_xdigit_value (*p);
1776 error_detail = _("hexadecimal digit or '}' expected");
1787 for (i = 0; i < 2; i++)
1789 h = g_ascii_xdigit_value (*p);
1792 error_detail = _("hexadecimal digit expected");
1799 data->type = REPL_TYPE_STRING;
1800 data->text = g_new0 (gchar, 8);
1801 g_unichar_to_utf8 (x, data->text);
1805 data->type = REPL_TYPE_CHANGE_CASE;
1806 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1810 data->type = REPL_TYPE_CHANGE_CASE;
1811 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1815 data->type = REPL_TYPE_CHANGE_CASE;
1816 data->change_case = CHANGE_CASE_LOWER;
1820 data->type = REPL_TYPE_CHANGE_CASE;
1821 data->change_case = CHANGE_CASE_UPPER;
1825 data->type = REPL_TYPE_CHANGE_CASE;
1826 data->change_case = CHANGE_CASE_NONE;
1832 error_detail = _("missing '<' in symbolic reference");
1841 error_detail = _("unfinished symbolic reference");
1848 error_detail = _("zero-length symbolic reference");
1851 if (g_ascii_isdigit (*q))
1856 h = g_ascii_digit_value (*q);
1859 error_detail = _("digit expected");
1868 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1875 if (!g_ascii_isalnum (*r))
1877 error_detail = _("illegal symbolic reference");
1884 data->text = g_strndup (q, p - q);
1885 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1890 /* if \0 is followed by a number is an octal number representing a
1891 * character, else it is a numeric reference. */
1892 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1895 p = g_utf8_next_char (p);
1908 for (i = 0; i < 3; i++)
1910 h = g_ascii_digit_value (*p);
1920 if (i == 2 && base == 10)
1926 if (base == 8 || i == 3)
1928 data->type = REPL_TYPE_STRING;
1929 data->text = g_new0 (gchar, 8);
1930 g_unichar_to_utf8 (x, data->text);
1934 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1939 error_detail = _("stray final '\\'");
1943 error_detail = _("unknown escape sequence");
1950 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1951 tmp_error = g_error_new (G_REGEX_ERROR,
1952 G_REGEX_ERROR_REPLACE,
1953 _("Error while parsing replacement "
1954 "text \"%s\" at char %lu: %s"),
1956 (gulong)(p - replacement),
1958 g_propagate_error (error, tmp_error);
1964 split_replacement (const gchar *replacement,
1968 InterpolationData *data;
1969 const gchar *p, *start;
1971 start = p = replacement;
1976 data = g_new0 (InterpolationData, 1);
1977 start = p = expand_escape (replacement, p, data, error);
1980 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1982 free_interpolation_data (data);
1986 list = g_list_prepend (list, data);
1991 if (*p == '\\' || *p == '\0')
1995 data = g_new0 (InterpolationData, 1);
1996 data->text = g_strndup (start, p - start);
1997 data->type = REPL_TYPE_STRING;
1998 list = g_list_prepend (list, data);
2004 return g_list_reverse (list);
2007 /* Change the case of c based on change_case. */
2008 #define CHANGE_CASE(c, change_case) \
2009 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2010 g_unichar_tolower (c) : \
2011 g_unichar_toupper (c))
2014 string_append (GString *string,
2016 ChangeCase *change_case)
2020 if (text[0] == '\0')
2023 if (*change_case == CHANGE_CASE_NONE)
2025 g_string_append (string, text);
2027 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2029 c = g_utf8_get_char (text);
2030 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2031 g_string_append (string, g_utf8_next_char (text));
2032 *change_case = CHANGE_CASE_NONE;
2036 while (*text != '\0')
2038 c = g_utf8_get_char (text);
2039 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2040 text = g_utf8_next_char (text);
2046 interpolate_replacement (const GRegex *regex,
2047 const gchar *string,
2052 InterpolationData *idata;
2054 ChangeCase change_case = CHANGE_CASE_NONE;
2056 for (list = data; list; list = list->next)
2059 switch (idata->type)
2061 case REPL_TYPE_STRING:
2062 string_append (result, idata->text, &change_case);
2064 case REPL_TYPE_CHARACTER:
2065 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2066 if (change_case & CHANGE_CASE_SINGLE_MASK)
2067 change_case = CHANGE_CASE_NONE;
2069 case REPL_TYPE_NUMERIC_REFERENCE:
2070 match = g_regex_fetch (regex, idata->num, string);
2073 string_append (result, match, &change_case);
2077 case REPL_TYPE_SYMBOLIC_REFERENCE:
2078 match = g_regex_fetch_named (regex, idata->text, string);
2081 string_append (result, match, &change_case);
2085 case REPL_TYPE_CHANGE_CASE:
2086 change_case = idata->change_case;
2095 * g_regex_expand_references:
2096 * @regex: #GRegex structure used in last match.
2097 * @string: the string on which the last match was made.
2098 * @string_to_expand: the string to expand.
2099 * @error: location to store the error occuring, or NULL to ignore errors.
2101 * Returns a new string containing the text in @string_to_expand with
2102 * references expanded. References refer to the last match done with
2103 * @string against @regex and have the same syntax used by g_regex_replace().
2105 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
2106 * passed to g_regex_new().
2108 * Returns: the expanded string, or %NULL if an error occurred.
2113 g_regex_expand_references (GRegex *regex,
2114 const gchar *string,
2115 const gchar *string_to_expand,
2120 GError *tmp_error = NULL;
2122 g_return_val_if_fail (regex != NULL, NULL);
2123 g_return_val_if_fail (string != NULL, NULL);
2124 g_return_val_if_fail (string_to_expand != NULL, NULL);
2125 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2127 list = split_replacement (string_to_expand, &tmp_error);
2128 if (tmp_error != NULL)
2130 g_propagate_error (error, tmp_error);
2134 result = g_string_sized_new (strlen (string_to_expand));
2135 interpolate_replacement (regex, string, result, list);
2137 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2140 return g_string_free (result, FALSE);
2145 * @regex: a #GRegex structure.
2146 * @string: the string to perform matches against.
2147 * @string_len: the length of @string, or -1 if @string is nul-terminated.
2148 * @start_position: starting index of the string to match.
2149 * @replacement: text to replace each match with.
2150 * @match_options: options for the match.
2151 * @error: location to store the error occuring, or NULL to ignore errors.
2153 * Replaces all occurances of the pattern in @regex with the
2154 * replacement text. Backreferences of the form '\number' or '\g<number>'
2155 * in the replacement text are interpolated by the number-th captured
2156 * subexpression of the match, '\g<name>' refers to the captured subexpression
2157 * with the given name. '\0' refers to the complete match, but '\0' followed
2158 * by a number is the octal representation of a character. To include a
2159 * literal '\' in the replacement, write '\\'.
2160 * There are also escapes that changes the case of the following text:
2163 * <varlistentry><term>\l</term>
2165 * <para>Convert to lower case the next character</para>
2168 * <varlistentry><term>\u</term>
2170 * <para>Convert to upper case the next character</para>
2173 * <varlistentry><term>\L</term>
2175 * <para>Convert to lower case till \E</para>
2178 * <varlistentry><term>\U</term>
2180 * <para>Convert to upper case till \E</para>
2183 * <varlistentry><term>\E</term>
2185 * <para>End case modification</para>
2190 * If you do not need to use backreferences use g_regex_replace_literal().
2192 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2193 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2194 * you can use g_regex_replace_literal().
2196 * Setting @start_position differs from just passing over a shortened string
2197 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2198 * with any kind of lookbehind assertion, such as "\b".
2200 * Returns: a newly allocated string containing the replacements.
2205 g_regex_replace (GRegex *regex,
2206 const gchar *string,
2208 gint start_position,
2209 const gchar *replacement,
2210 GRegexMatchFlags match_options,
2215 GError *tmp_error = NULL;
2217 g_return_val_if_fail (regex != NULL, NULL);
2218 g_return_val_if_fail (string != NULL, NULL);
2219 g_return_val_if_fail (start_position >= 0, NULL);
2220 g_return_val_if_fail (replacement != NULL, NULL);
2221 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2222 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2224 list = split_replacement (replacement, &tmp_error);
2225 if (tmp_error != NULL)
2227 g_propagate_error (error, tmp_error);
2231 result = g_regex_replace_eval (regex,
2232 string, string_len, start_position,
2234 interpolate_replacement,
2237 if (tmp_error != NULL)
2238 g_propagate_error (error, tmp_error);
2240 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2247 literal_replacement (const GRegex *regex,
2248 const gchar *string,
2252 g_string_append (result, data);
2257 * g_regex_replace_literal:
2258 * @regex: a #GRegex structure.
2259 * @string: the string to perform matches against.
2260 * @string_len: the length of @string, or -1 if @string is nul-terminated.
2261 * @start_position: starting index of the string to match.
2262 * @replacement: text to replace each match with.
2263 * @match_options: options for the match.
2264 * @error: location to store the error occuring, or NULL to ignore errors.
2266 * Replaces all occurances of the pattern in @regex with the
2267 * replacement text. @replacement is replaced literally, to
2268 * include backreferences use g_regex_replace().
2270 * Setting @start_position differs from just passing over a shortened string
2271 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2272 * with any kind of lookbehind assertion, such as "\b".
2274 * Returns: a newly allocated string containing the replacements.
2279 g_regex_replace_literal (GRegex *regex,
2280 const gchar *string,
2282 gint start_position,
2283 const gchar *replacement,
2284 GRegexMatchFlags match_options,
2287 g_return_val_if_fail (replacement != NULL, NULL);
2288 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2290 return g_regex_replace_eval (regex,
2291 string, string_len, start_position,
2293 literal_replacement,
2294 (gpointer)replacement,
2299 * g_regex_replace_eval:
2300 * @regex: a #GRegex structure from g_regex_new().
2301 * @string: string to perform matches against.
2302 * @string_len: the length of @string, or -1 if @string is nul-terminated.
2303 * @start_position: starting index of the string to match.
2304 * @match_options: Options for the match.
2305 * @eval: a function to call for each match.
2306 * @user_data: user data to pass to the function.
2307 * @error: location to store the error occuring, or NULL to ignore errors.
2309 * Replaces occurances of the pattern in regex with the output of @eval
2310 * for that occurance.
2312 * Setting @start_position differs from just passing over a shortened string
2313 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2314 * with any kind of lookbehind assertion, such as "\b".
2316 * Returns: a newly allocated string containing the replacements.
2321 g_regex_replace_eval (GRegex *regex,
2322 const gchar *string,
2324 gint start_position,
2325 GRegexMatchFlags match_options,
2326 GRegexEvalCallback eval,
2332 gboolean done = FALSE;
2333 GError *tmp_error = NULL;
2335 g_return_val_if_fail (regex != NULL, NULL);
2336 g_return_val_if_fail (string != NULL, NULL);
2337 g_return_val_if_fail (start_position >= 0, NULL);
2338 g_return_val_if_fail (eval != NULL, NULL);
2339 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2341 regex_lazy_init_match (regex, 0);
2344 string_len = strlen(string);
2346 /* clear out the regex for reuse, just in case */
2347 g_regex_clear (regex);
2349 result = g_string_sized_new (string_len);
2351 /* run down the string making matches. */
2353 g_regex_match_next_full (regex, string, string_len,
2354 start_position, match_options, &tmp_error))
2356 g_string_append_len (result,
2358 regex->match->offsets[0] - str_pos);
2359 done = (*eval) (regex, string, result, user_data);
2360 str_pos = regex->match->offsets[1];
2363 if (tmp_error != NULL)
2365 g_propagate_error (error, tmp_error);
2366 g_string_free (result, TRUE);
2370 g_string_append_len (result, string + str_pos, string_len - str_pos);
2372 return g_string_free (result, FALSE);
2376 * g_regex_escape_string:
2377 * @string: the string to escape.
2378 * @length: the length of @string, or -1 if @string is nul-terminated.
2380 * Escapes the special characters used for regular expressions in @string,
2381 * for instance "a.b*c" becomes "a\.b\*c". This function is useful to
2382 * dynamically generate regular expressions.
2384 * @string can contain NULL characters that are replaced with "\0", in this
2385 * case remember to specify the correct length of @string in @length.
2387 * Returns: a newly allocated escaped string.
2392 g_regex_escape_string (const gchar *string,
2396 const char *p, *piece_start, *end;
2398 g_return_val_if_fail (string != NULL, NULL);
2401 length = strlen (string);
2403 end = string + length;
2404 p = piece_start = string;
2405 escaped = g_string_sized_new (length + 1);
2426 if (p != piece_start)
2427 /* copy the previous piece. */
2428 g_string_append_len (escaped, piece_start, p - piece_start);
2429 g_string_append_c (escaped, '\\');
2431 g_string_append_c (escaped, '0');
2433 g_string_append_c (escaped, *p);
2437 p = g_utf8_next_char (p);
2441 if (piece_start < end)
2442 g_string_append_len (escaped, piece_start, end - piece_start);
2444 return g_string_free (escaped, FALSE);
2447 #define __G_REGEX_C__
2448 #include "galiasdef.c"