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
27 #include <glib/gi18n.h>
30 #ifdef USE_SYSTEM_PCRE
33 #include "pcre/pcre.h"
38 /* Mask of all the possible values for GRegexCompileFlags. */
39 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
44 G_REGEX_DOLLAR_ENDONLY | \
47 G_REGEX_NO_AUTO_CAPTURE | \
50 G_REGEX_NEWLINE_CR | \
51 G_REGEX_NEWLINE_LF | \
54 /* Mask of all the possible values for GRegexMatchFlags. */
55 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
56 G_REGEX_MATCH_NOTBOL | \
57 G_REGEX_MATCH_NOTEOL | \
58 G_REGEX_MATCH_NOTEMPTY | \
59 G_REGEX_MATCH_PARTIAL | \
60 G_REGEX_MATCH_NEWLINE_CR | \
61 G_REGEX_MATCH_NEWLINE_LF | \
62 G_REGEX_MATCH_NEWLINE_CRLF | \
63 G_REGEX_MATCH_NEWLINE_ANY)
65 /* if the string is in UTF-8 use g_utf8_ functions, else use
67 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
68 g_utf8_next_char (s) : \
70 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
71 g_utf8_prev_char (s) : \
76 GRegex *regex; /* the regex */
77 GRegexMatchFlags match_opts; /* options used at match time on the regex */
78 gint matches; /* number of matching sub patterns */
79 gint pos; /* position in the string where last match left off */
80 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
81 gint n_offsets; /* number of offsets */
82 gint *workspace; /* workspace for pcre_dfa_exec() */
83 gint n_workspace; /* number of workspace elements */
84 const gchar *string; /* string passed to the match function */
85 gssize string_len; /* length of string */
90 volatile guint ref_count; /* the ref count for the immutable part */
91 gchar *pattern; /* the pattern */
92 pcre *pcre_re; /* compiled form of the pattern */
93 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
94 GRegexMatchFlags match_opts; /* options used at match time on the regex */
95 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
98 /* TRUE if ret is an error code, FALSE otherwise. */
99 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
101 typedef struct _InterpolationData InterpolationData;
102 static gboolean interpolation_list_needs_match (GList *list);
103 static gboolean interpolate_replacement (const GMatchInfo *match_info,
106 static GList *split_replacement (const gchar *replacement,
108 static void free_interpolation_data (InterpolationData *data);
112 match_error (gint errcode)
116 case PCRE_ERROR_NOMATCH:
119 case PCRE_ERROR_NULL:
120 /* NULL argument, this should not happen in GRegex */
121 g_warning ("A NULL argument was passed to PCRE");
123 case PCRE_ERROR_BADOPTION:
124 return "bad options";
125 case PCRE_ERROR_BADMAGIC:
126 return _("corrupted object");
127 case PCRE_ERROR_UNKNOWN_OPCODE:
128 return N_("internal error or corrupted object");
129 case PCRE_ERROR_NOMEMORY:
130 return _("out of memory");
131 case PCRE_ERROR_NOSUBSTRING:
132 /* not used by pcre_exec() */
134 case PCRE_ERROR_MATCHLIMIT:
135 return _("backtracking limit reached");
136 case PCRE_ERROR_CALLOUT:
137 /* callouts are not implemented */
139 case PCRE_ERROR_BADUTF8:
140 case PCRE_ERROR_BADUTF8_OFFSET:
141 /* we do not check if strings are valid */
143 case PCRE_ERROR_PARTIAL:
146 case PCRE_ERROR_BADPARTIAL:
147 return _("the pattern contains items not supported for partial matching");
148 case PCRE_ERROR_INTERNAL:
149 return _("internal error");
150 case PCRE_ERROR_BADCOUNT:
151 /* negative ovecsize, this should not happen in GRegex */
152 g_warning ("A negative ovecsize was passed to PCRE");
154 case PCRE_ERROR_DFA_UITEM:
155 return _("the pattern contains items not supported for partial matching");
156 case PCRE_ERROR_DFA_UCOND:
157 return _("back references as conditions are not supported for partial matching");
158 case PCRE_ERROR_DFA_UMLIMIT:
159 /* the match_field field is not used in GRegex */
161 case PCRE_ERROR_DFA_WSSIZE:
162 /* handled expanding the workspace */
164 case PCRE_ERROR_DFA_RECURSE:
165 case PCRE_ERROR_RECURSIONLIMIT:
166 return _("recursion limit reached");
167 case PCRE_ERROR_NULLWSLIMIT:
168 return _("workspace limit for empty substrings reached");
169 case PCRE_ERROR_BADNEWLINE:
170 return _("invalid combination of newline flags");
174 return _("unknown error");
181 match_info_new (const GRegex *regex,
188 GMatchInfo *match_info;
191 string_len = strlen (string);
193 match_info = g_new0 (GMatchInfo, 1);
194 match_info->regex = g_regex_ref ((GRegex *)regex);
195 match_info->string = string;
196 match_info->string_len = string_len;
197 match_info->matches = PCRE_ERROR_NOMATCH;
198 match_info->pos = start_position;
199 match_info->match_opts = match_options;
203 /* These values should be enough for most cases, if they are not
204 * enough g_regex_match_all_full() will expand them. */
205 match_info->n_offsets = 24;
206 match_info->n_workspace = 100;
207 match_info->workspace = g_new (gint, match_info->n_workspace);
212 pcre_fullinfo (regex->pcre_re, regex->extra,
213 PCRE_INFO_CAPTURECOUNT, &capture_count);
214 match_info->n_offsets = (capture_count + 1) * 3;
216 match_info->offsets = g_new0 (gint, match_info->n_offsets);
222 * g_match_info_get_regex:
223 * @match_info: a #GMatchInfo
225 * Returns #GRegex object used in @match_info. It belongs to Glib
226 * and must not be freed. Use g_regex_ref() if you need to keep it
227 * after you free @match_info object.
229 * Returns: #GRegex object used in @match_info
234 g_match_info_get_regex (const GMatchInfo *match_info)
236 g_return_val_if_fail (match_info != NULL, NULL);
237 return match_info->regex;
241 * g_match_info_get_string:
242 * @match_info: a #GMatchInfo
244 * Returns the string searched with @match_info. This is the
245 * string passed to g_regex_match() or g_regex_replace() so
246 * you may not free it before calling this function.
248 * Returns: the string searched with @match_info
253 g_match_info_get_string (const GMatchInfo *match_info)
255 g_return_val_if_fail (match_info != NULL, NULL);
256 return match_info->string;
261 * @match_info: a #GMatchInfo
263 * Frees all the memory associated with the #GMatchInfo structure.
268 g_match_info_free (GMatchInfo *match_info)
272 g_regex_unref (match_info->regex);
273 g_free (match_info->offsets);
274 g_free (match_info->workspace);
281 * @match_info: a #GMatchInfo structure
282 * @error: location to store the error occuring, or %NULL to ignore errors
284 * Scans for the next match using the same parameters of the previous
285 * call to g_regex_match_full() or g_regex_match() that returned
288 * The match is done on the string passed to the match function, so you
289 * cannot free it before calling this function.
291 * Returns: %TRUE is the string matched, %FALSE otherwise
296 g_match_info_next (GMatchInfo *match_info,
299 g_return_val_if_fail (match_info != NULL, FALSE);
300 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
301 g_return_val_if_fail (match_info->pos >= 0, FALSE);
303 gint opts = match_info->regex->match_opts | match_info->match_opts;
305 match_info->matches = pcre_exec (match_info->regex->pcre_re,
306 match_info->regex->extra,
308 match_info->string_len,
310 match_info->regex->match_opts |
311 match_info->match_opts,
313 match_info->n_offsets);
314 if (IS_PCRE_ERROR (match_info->matches))
316 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
317 _("Error while matching regular expression %s: %s"),
318 match_info->regex->pattern, match_error (match_info->matches));
322 /* avoid infinite loops if the pattern is an empty string or something
324 if (match_info->pos == match_info->offsets[1])
326 if (match_info->pos > match_info->string_len)
328 /* we have reached the end of the string */
329 match_info->pos = -1;
330 match_info->matches = PCRE_ERROR_NOMATCH;
334 match_info->pos = NEXT_CHAR (match_info->regex,
335 &match_info->string[match_info->pos]) -
340 match_info->pos = match_info->offsets[1];
343 return match_info->matches >= 0;
347 * g_match_info_matches:
348 * @match_info: a #GMatchInfo structure
350 * Returns wether the previous match operation succeeded.
352 * Returns: %TRUE if the previous match operation succeeded,
358 g_match_info_matches (const GMatchInfo *match_info)
360 g_return_val_if_fail (match_info != NULL, FALSE);
362 return match_info->matches >= 0;
366 * g_match_info_get_match_count:
367 * @match_info: a #GMatchInfo structure
369 * Retrieves the number of matched substrings (including substring 0,
370 * that is the whole matched text), so 1 is returned if the pattern
371 * has no substrings in it and 0 is returned if the match failed.
373 * If the last match was obtained using the DFA algorithm, that is
374 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
375 * count is not that of the number of capturing parentheses but that of
376 * the number of matched substrings.
378 * Returns: Number of matched substrings, or -1 if an error occurred
383 g_match_info_get_match_count (const GMatchInfo *match_info)
385 g_return_val_if_fail (match_info, -1);
387 if (match_info->matches == PCRE_ERROR_NOMATCH)
390 else if (match_info->matches < PCRE_ERROR_NOMATCH)
395 return match_info->matches;
399 * g_match_info_is_partial_match:
400 * @match_info: a #GMatchInfo structure
402 * Usually if the string passed to g_regex_match*() matches as far as
403 * it goes, but is too short to match the entire pattern, %FALSE is
404 * returned. There are circumstances where it might be helpful to
405 * distinguish this case from other cases in which there is no match.
407 * Consider, for example, an application where a human is required to
408 * type in data for a field with specific formatting requirements. An
409 * example might be a date in the form ddmmmyy, defined by the pattern
410 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
411 * If the application sees the user’s keystrokes one by one, and can
412 * check that what has been typed so far is potentially valid, it is
413 * able to raise an error as soon as a mistake is made.
415 * GRegex supports the concept of partial matching by means of the
416 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
417 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
418 * for a complete match, %FALSE otherwise. But, when these functions
419 * return %FALSE, you can check if the match was partial calling
420 * g_match_info_is_partial_match().
422 * When using partial matching you cannot use g_match_info_fetch*().
424 * Because of the way certain internal optimizations are implemented
425 * the partial matching algorithm cannot be used with all patterns.
426 * So repeated single characters such as "a{2,4}" and repeated single
427 * meta-sequences such as "\d+" are not permitted if the maximum number
428 * of occurrences is greater than one. Optional items such as "\d?"
429 * (where the maximum is one) are permitted. Quantifiers with any values
430 * are permitted after parentheses, so the invalid examples above can be
431 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
432 * for a pattern that does not conform to the restrictions, matching
433 * functions return an error.
435 * Returns: %TRUE if the match was partial, %FALSE otherwise
440 g_match_info_is_partial_match (const GMatchInfo *match_info)
442 g_return_val_if_fail (match_info != NULL, FALSE);
444 return match_info->matches == PCRE_ERROR_PARTIAL;
448 * g_match_info_expand_references:
449 * @match_info: a #GMatchInfo or %NULL
450 * @string_to_expand: the string to expand
451 * @error: location to store the error occuring, or %NULL to ignore errors
453 * Returns a new string containing the text in @string_to_expand with
454 * references and escape sequences expanded. References refer to the last
455 * match done with @string against @regex and have the same syntax used by
458 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
459 * passed to g_regex_new().
461 * The backreferences are extracted from the string passed to the match
462 * function, so you cannot call this function after freeing the string.
464 * @match_info may be %NULL in which case @string_to_expand must not
465 * contain references. For instance "foo\n" does not refer to an actual
466 * pattern and '\n' merely will be replaced with \n character,
467 * while to expand "\0" (whole match) one needs the result of a match.
468 * Use g_regex_check_replacement() to find out whether @string_to_expand
469 * contains references.
471 * Returns: the expanded string, or %NULL if an error occurred
476 g_match_info_expand_references (const GMatchInfo *match_info,
477 const gchar *string_to_expand,
482 GError *tmp_error = NULL;
484 g_return_val_if_fail (string_to_expand != NULL, NULL);
485 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
487 list = split_replacement (string_to_expand, &tmp_error);
488 if (tmp_error != NULL)
490 g_propagate_error (error, tmp_error);
494 if (!match_info && interpolation_list_needs_match (list))
496 g_critical ("String '%s' contains references to the match, can't "
497 "expand references without GMatchInfo object",
502 result = g_string_sized_new (strlen (string_to_expand));
503 interpolate_replacement (match_info, result, list);
505 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
508 return g_string_free (result, FALSE);
512 * g_match_info_fetch:
513 * @match_info: #GMatchInfo structure
514 * @match_num: number of the sub expression
516 * Retrieves the text matching the @match_num<!-- -->'th capturing
517 * parentheses. 0 is the full text of the match, 1 is the first paren
518 * set, 2 the second, and so on.
520 * If @match_num is a valid sub pattern but it didn't match anything
521 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
522 * string is returned.
524 * If the match was obtained using the DFA algorithm, that is using
525 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
526 * string is not that of a set of parentheses but that of a matched
527 * substring. Substrings are matched in reverse order of length, so
528 * 0 is the longest match.
530 * The string is fetched from the string passed to the match function,
531 * so you cannot call this function after freeing the string.
533 * Returns: The matched substring, or %NULL if an error occurred.
534 * You have to free the string yourself
539 g_match_info_fetch (const GMatchInfo *match_info,
542 /* we cannot use pcre_get_substring() because it allocates the
543 * string using pcre_malloc(). */
547 g_return_val_if_fail (match_info != NULL, NULL);
548 g_return_val_if_fail (match_num >= 0, NULL);
550 /* match_num does not exist or it didn't matched, i.e. matching "b"
551 * against "(a)?b" then group 0 is empty. */
552 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
554 else if (start == -1)
555 match = g_strdup ("");
557 match = g_strndup (&match_info->string[start], end - start);
563 * g_match_info_fetch_pos:
564 * @match_info: #GMatchInfo structure
565 * @match_num: number of the sub expression
566 * @start_pos: pointer to location where to store the start position
567 * @end_pos: pointer to location where to store the end position
569 * Retrieves the position of the @match_num<!-- -->'th capturing
570 * parentheses. 0 is the full text of the match, 1 is the first
571 * paren set, 2 the second, and so on.
573 * If @match_num is a valid sub pattern but it didn't match anything
574 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
575 * and @end_pos are set to -1 and %TRUE is returned.
577 * If the match was obtained using the DFA algorithm, that is using
578 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
579 * position is not that of a set of parentheses but that of a matched
580 * substring. Substrings are matched in reverse order of length, so
581 * 0 is the longest match.
583 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
584 * the position cannot be fetched, @start_pos and @end_pos are left
590 g_match_info_fetch_pos (const GMatchInfo *match_info,
595 g_return_val_if_fail (match_info != NULL, FALSE);
596 g_return_val_if_fail (match_num >= 0, FALSE);
598 /* make sure the sub expression number they're requesting is less than
599 * the total number of sub expressions that were matched. */
600 if (match_num >= match_info->matches)
603 if (start_pos != NULL)
604 *start_pos = match_info->offsets[2 * match_num];
607 *end_pos = match_info->offsets[2 * match_num + 1];
613 * Returns number of first matched subpattern with name @name.
614 * There may be more than one in case when DUPNAMES is used,
615 * and not all subpatterns with that name match;
616 * pcre_get_stringnumber() does not work in that case.
619 get_matched_substring_number (const GMatchInfo *match_info,
626 #if PCRE_MAJOR > 7 || PCRE_MINOR >= 2
627 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
628 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
631 /* This code is copied from pcre_get.c: get_first_set() */
632 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
640 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
642 gint n = (entry[0] << 8) + entry[1];
643 if (match_info->offsets[n*2] >= 0)
647 return (first[0] << 8) + first[1];
651 * g_match_info_fetch_named:
652 * @match_info: #GMatchInfo structure
653 * @name: name of the subexpression
655 * Retrieves the text matching the capturing parentheses named @name.
657 * If @name is a valid sub pattern name but it didn't match anything
658 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
659 * then an empty string is returned.
661 * The string is fetched from the string passed to the match function,
662 * so you cannot call this function after freeing the string.
664 * Returns: The matched substring, or %NULL if an error occurred.
665 * You have to free the string yourself
670 g_match_info_fetch_named (const GMatchInfo *match_info,
673 /* we cannot use pcre_get_named_substring() because it allocates the
674 * string using pcre_malloc(). */
677 g_return_val_if_fail (match_info != NULL, NULL);
678 g_return_val_if_fail (name != NULL, NULL);
680 num = get_matched_substring_number (match_info, name);
684 return g_match_info_fetch (match_info, num);
688 * g_match_info_fetch_named_pos:
689 * @match_info: #GMatchInfo structure
690 * @name: name of the subexpression
691 * @start_pos: pointer to location where to store the start position
692 * @end_pos: pointer to location where to store the end position
694 * Retrieves the position of the capturing parentheses named @name.
696 * If @name is a valid sub pattern name but it didn't match anything
697 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
698 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
700 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
701 * the position cannot be fetched, @start_pos and @end_pos are left
707 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
714 g_return_val_if_fail (match_info != NULL, FALSE);
715 g_return_val_if_fail (name != NULL, FALSE);
717 num = get_matched_substring_number (match_info, name);
721 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
725 * g_match_info_fetch_all:
726 * @match_info: a #GMatchInfo structure
728 * Bundles up pointers to each of the matching substrings from a match
729 * and stores them in an array of gchar pointers. The first element in
730 * the returned array is the match number 0, i.e. the entire matched
733 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
734 * "b" against "(a)?b") then an empty string is inserted.
736 * If the last match was obtained using the DFA algorithm, that is using
737 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
738 * strings are not that matched by sets of parentheses but that of the
739 * matched substring. Substrings are matched in reverse order of length,
740 * so the first one is the longest match.
742 * The strings are fetched from the string passed to the match function,
743 * so you cannot call this function after freeing the string.
745 * Returns: a %NULL-terminated array of gchar * pointers. It must be
746 * freed using g_strfreev(). If the previous match failed %NULL is
752 g_match_info_fetch_all (const GMatchInfo *match_info)
754 /* we cannot use pcre_get_substring_list() because the returned value
755 * isn't suitable for g_strfreev(). */
759 g_return_val_if_fail (match_info != NULL, FALSE);
761 if (match_info->matches < 0)
764 result = g_new (gchar *, match_info->matches + 1);
765 for (i = 0; i < match_info->matches; i++)
766 result[i] = g_match_info_fetch (match_info, i);
776 g_regex_error_quark (void)
778 static GQuark error_quark = 0;
780 if (error_quark == 0)
781 error_quark = g_quark_from_static_string ("g-regex-error-quark");
790 * Increases reference count of @regex by 1.
797 g_regex_ref (GRegex *regex)
799 g_return_val_if_fail (regex != NULL, NULL);
800 g_atomic_int_inc ((gint*) ®ex->ref_count);
808 * Decreases reference count of @regex by 1. When reference count drops
809 * to zero, it frees all the memory associated with the regex structure.
814 g_regex_unref (GRegex *regex)
816 g_return_if_fail (regex != NULL);
818 if (g_atomic_int_exchange_and_add ((gint *) ®ex->ref_count, -1) - 1 == 0)
820 g_free (regex->pattern);
821 if (regex->pcre_re != NULL)
822 pcre_free (regex->pcre_re);
823 if (regex->extra != NULL)
824 pcre_free (regex->extra);
831 * @pattern: the regular expression
832 * @compile_options: compile options for the regular expression
833 * @match_options: match options for the regular expression
834 * @error: return location for a #GError
836 * Compiles the regular expression to an internal form, and does
837 * the initial setup of the #GRegex structure.
839 * Returns: a #GRegex structure. Call g_regex_unref() when you
845 g_regex_new (const gchar *pattern,
846 GRegexCompileFlags compile_options,
847 GRegexMatchFlags match_options,
854 gboolean optimize = FALSE;
855 static gboolean initialized = FALSE;
857 g_return_val_if_fail (pattern != NULL, NULL);
858 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
859 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
860 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
867 pcre_config (PCRE_CONFIG_UTF8, &support);
870 msg = N_("PCRE library is compiled without UTF8 support");
872 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
876 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
879 msg = N_("PCRE library is compiled without UTF8 properties support");
881 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
888 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
889 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
890 if (compile_options & G_REGEX_OPTIMIZE)
893 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
894 * instead uses UTF-8 only if required with PCRE_UTF8. */
895 if (compile_options & G_REGEX_RAW)
898 compile_options &= ~G_REGEX_RAW;
903 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
904 match_options |= PCRE_NO_UTF8_CHECK;
907 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
908 * not for the system one. */
909 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
910 !(compile_options & G_REGEX_NEWLINE_LF))
912 compile_options |= PCRE_NEWLINE_ANY;
915 /* compile the pattern */
916 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
918 /* if the compilation failed, set the error member and return
922 GError *tmp_error = g_error_new (G_REGEX_ERROR,
923 G_REGEX_ERROR_COMPILE,
924 _("Error while compiling regular "
925 "expression %s at char %d: %s"),
926 pattern, erroffset, errmsg);
927 g_propagate_error (error, tmp_error);
932 #if PCRE_MAJOR > 7 || PCRE_MINOR >= 2
933 if (!(compile_options & G_REGEX_DUPNAMES))
935 gboolean jchanged = FALSE;
936 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
938 compile_options |= G_REGEX_DUPNAMES;
942 regex = g_new0 (GRegex, 1);
943 regex->ref_count = 1;
944 regex->pattern = g_strdup (pattern);
946 regex->compile_opts = compile_options;
947 regex->match_opts = match_options;
951 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
954 GError *tmp_error = g_error_new (G_REGEX_ERROR,
955 G_REGEX_ERROR_OPTIMIZE,
956 _("Error while optimizing "
957 "regular expression %s: %s"),
960 g_propagate_error (error, tmp_error);
969 * g_regex_get_pattern:
970 * @regex: a #GRegex structure
972 * Gets the pattern string associated with @regex, i.e. a copy of
973 * the string passed to g_regex_new().
975 * Returns: the pattern of @regex
980 g_regex_get_pattern (const GRegex *regex)
982 g_return_val_if_fail (regex != NULL, NULL);
984 return regex->pattern;
988 * g_regex_get_max_backref:
991 * Returns the number of the highest back reference
992 * in the pattern, or 0 if the pattern does not contain
995 * Returns: the number of the highest back reference
1000 g_regex_get_max_backref (const GRegex *regex)
1004 pcre_fullinfo (regex->pcre_re, regex->extra,
1005 PCRE_INFO_BACKREFMAX, &value);
1011 * g_regex_get_capture_count:
1014 * Returns the number of capturing subpatterns in the pattern.
1016 * Returns: the number of capturing subpatterns
1021 g_regex_get_capture_count (const GRegex *regex)
1025 pcre_fullinfo (regex->pcre_re, regex->extra,
1026 PCRE_INFO_CAPTURECOUNT, &value);
1032 * g_regex_match_simple:
1033 * @pattern: the regular expression
1034 * @string: the string to scan for matches
1035 * @compile_options: compile options for the regular expression
1036 * @match_options: match options
1038 * Scans for a match in @string for @pattern.
1040 * This function is equivalent to g_regex_match() but it does not
1041 * require to compile the pattern with g_regex_new(), avoiding some
1042 * lines of code when you need just to do a match without extracting
1043 * substrings, capture counts, and so on.
1045 * If this function is to be called on the same @pattern more than
1046 * once, it's more efficient to compile the pattern once with
1047 * g_regex_new() and then use g_regex_match().
1049 * Returns: %TRUE is the string matched, %FALSE otherwise
1054 g_regex_match_simple (const gchar *pattern,
1055 const gchar *string,
1056 GRegexCompileFlags compile_options,
1057 GRegexMatchFlags match_options)
1062 regex = g_regex_new (pattern, compile_options, 0, NULL);
1065 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1066 g_regex_unref (regex);
1072 * @regex: a #GRegex structure from g_regex_new()
1073 * @string: the string to scan for matches
1074 * @match_options: match options
1075 * @match_info: pointer to location where to store the #GMatchInfo,
1076 * or %NULL if you do not need it
1078 * Scans for a match in string for the pattern in @regex.
1079 * The @match_options are combined with the match options specified
1080 * when the @regex structure was created, letting you have more
1081 * flexibility in reusing #GRegex structures.
1083 * A #GMatchInfo structure, used to get information on the match,
1084 * is stored in @match_info if not %NULL. Note that if @match_info
1085 * is not %NULL then it is created even if the function returns %FALSE,
1086 * i.e. you must free it regardless if regular expression actually matched.
1088 * To retrieve all the non-overlapping matches of the pattern in
1089 * string you can use g_match_info_next().
1091 * <informalexample><programlisting>
1093 * print_uppercase_words (const gchar *string)
1095 * /* Print all uppercase-only words. */
1097 * GMatchInfo *match_info;
1099 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1100 * g_regex_match (regex, string, 0, &match_info);
1101 * while (g_match_info_matches (match_info))
1103 * gchar *word = g_match_info_fetch (match_info, 0);
1104 * g_print ("Found: %s\n", word);
1106 * g_match_info_next (match_info, NULL);
1108 * g_match_info_free (match_info);
1109 * g_regex_unref (regex);
1111 * </programlisting></informalexample>
1113 * Returns: %TRUE is the string matched, %FALSE otherwise
1118 g_regex_match (const GRegex *regex,
1119 const gchar *string,
1120 GRegexMatchFlags match_options,
1121 GMatchInfo **match_info)
1123 return g_regex_match_full (regex, string, -1, 0, match_options,
1128 * g_regex_match_full:
1129 * @regex: a #GRegex structure from g_regex_new()
1130 * @string: the string to scan for matches
1131 * @string_len: the length of @string, or -1 if @string is nul-terminated
1132 * @start_position: starting index of the string to match
1133 * @match_options: match options
1134 * @match_info: pointer to location where to store the #GMatchInfo,
1135 * or %NULL if you do not need it
1136 * @error: location to store the error occuring, or %NULL to ignore errors
1138 * Scans for a match in string for the pattern in @regex.
1139 * The @match_options are combined with the match options specified
1140 * when the @regex structure was created, letting you have more
1141 * flexibility in reusing #GRegex structures.
1143 * Setting @start_position differs from just passing over a shortened
1144 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1145 * that begins with any kind of lookbehind assertion, such as "\b".
1147 * A #GMatchInfo structure, used to get information on the match, is
1148 * stored in @match_info if not %NULL. Note that if @match_info is
1149 * not %NULL then it is created even if the function returns %FALSE,
1150 * i.e. you must free it regardless if regular expression actually
1153 * @string is not copied and is used in #GMatchInfo internally. If
1154 * you use any #GMatchInfo method (except g_match_info_free()) after
1155 * freeing or modifying @string then the behaviour is undefined.
1157 * To retrieve all the non-overlapping matches of the pattern in
1158 * string you can use g_match_info_next().
1160 * <informalexample><programlisting>
1162 * print_uppercase_words (const gchar *string)
1164 * /* Print all uppercase-only words. */
1166 * GMatchInfo *match_info;
1167 * GError *error = NULL;
1169 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1170 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1171 * while (g_match_info_matches (match_info))
1173 * gchar *word = g_match_info_fetch (match_info, 0);
1174 * g_print ("Found: %s\n", word);
1176 * g_match_info_next (match_info, &error);
1178 * g_match_info_free (match_info);
1179 * g_regex_unref (regex);
1180 * if (error != NULL)
1182 * g_printerr ("Error while matching: %s\n", error->message);
1183 * g_error_free (error);
1186 * </programlisting></informalexample>
1188 * Returns: %TRUE is the string matched, %FALSE otherwise
1193 g_regex_match_full (const GRegex *regex,
1194 const gchar *string,
1196 gint start_position,
1197 GRegexMatchFlags match_options,
1198 GMatchInfo **match_info,
1204 g_return_val_if_fail (regex != NULL, FALSE);
1205 g_return_val_if_fail (string != NULL, FALSE);
1206 g_return_val_if_fail (start_position >= 0, FALSE);
1207 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1208 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1210 info = match_info_new (regex, string, string_len, start_position,
1211 match_options, FALSE);
1212 match_ok = g_match_info_next (info, error);
1213 if (match_info != NULL)
1216 g_match_info_free (info);
1222 * g_regex_match_all:
1223 * @regex: a #GRegex structure from g_regex_new()
1224 * @string: the string to scan for matches
1225 * @match_options: match options
1226 * @match_info: pointer to location where to store the #GMatchInfo,
1227 * or %NULL if you do not need it
1229 * Using the standard algorithm for regular expression matching only
1230 * the longest match in the string is retrieved. This function uses
1231 * a different algorithm so it can retrieve all the possible matches.
1232 * For more documentation see g_regex_match_all_full().
1234 * A #GMatchInfo structure, used to get information on the match, is
1235 * stored in @match_info if not %NULL. Note that if @match_info is
1236 * not %NULL then it is created even if the function returns %FALSE,
1237 * i.e. you must free it regardless if regular expression actually
1240 * Returns: %TRUE is the string matched, %FALSE otherwise
1245 g_regex_match_all (const GRegex *regex,
1246 const gchar *string,
1247 GRegexMatchFlags match_options,
1248 GMatchInfo **match_info)
1250 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1255 * g_regex_match_all_full:
1256 * @regex: a #GRegex structure from g_regex_new()
1257 * @string: the string to scan for matches
1258 * @string_len: the length of @string, or -1 if @string is nul-terminated
1259 * @start_position: starting index of the string to match
1260 * @match_options: match options
1261 * @match_info: pointer to location where to store the #GMatchInfo,
1262 * or %NULL if you do not need it
1263 * @error: location to store the error occuring, or %NULL to ignore errors
1265 * Using the standard algorithm for regular expression matching only
1266 * the longest match in the string is retrieved, it is not possibile
1267 * to obtain all the available matches. For instance matching
1268 * "<a> <b> <c>" against the pattern "<.*>"
1269 * you get "<a> <b> <c>".
1271 * This function uses a different algorithm (called DFA, i.e. deterministic
1272 * finite automaton), so it can retrieve all the possible matches, all
1273 * starting at the same point in the string. For instance matching
1274 * "<a> <b> <c>" against the pattern "<.*>"
1275 * you would obtain three matches: "<a> <b> <c>",
1276 * "<a> <b>" and "<a>".
1278 * The number of matched strings is retrieved using
1279 * g_match_info_get_match_count(). To obtain the matched strings and
1280 * their position you can use, respectively, g_match_info_fetch() and
1281 * g_match_info_fetch_pos(). Note that the strings are returned in
1282 * reverse order of length; that is, the longest matching string is
1285 * Note that the DFA algorithm is slower than the standard one and it
1286 * is not able to capture substrings, so backreferences do not work.
1288 * Setting @start_position differs from just passing over a shortened
1289 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1290 * that begins with any kind of lookbehind assertion, such as "\b".
1292 * A #GMatchInfo structure, used to get information on the match, is
1293 * stored in @match_info if not %NULL. Note that if @match_info is
1294 * not %NULL then it is created even if the function returns %FALSE,
1295 * i.e. you must free it regardless if regular expression actually
1298 * Returns: %TRUE is the string matched, %FALSE otherwise
1303 g_regex_match_all_full (const GRegex *regex,
1304 const gchar *string,
1306 gint start_position,
1307 GRegexMatchFlags match_options,
1308 GMatchInfo **match_info,
1314 g_return_val_if_fail (regex != NULL, FALSE);
1315 g_return_val_if_fail (string != NULL, FALSE);
1316 g_return_val_if_fail (start_position >= 0, FALSE);
1317 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1318 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1320 info = match_info_new (regex, string, string_len, start_position,
1321 match_options, TRUE);
1327 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1328 info->string, info->string_len,
1330 regex->match_opts | match_options,
1331 info->offsets, info->n_offsets,
1332 info->workspace, info->n_workspace);
1333 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1335 /* info->workspace is too small. */
1336 info->n_workspace *= 2;
1337 info->workspace = g_realloc (info->workspace,
1338 info->n_workspace * sizeof (gint));
1341 else if (info->matches == 0)
1343 /* info->offsets is too small. */
1344 info->n_offsets *= 2;
1345 info->offsets = g_realloc (info->offsets,
1346 info->n_offsets * sizeof (gint));
1349 else if (IS_PCRE_ERROR (info->matches))
1351 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1352 _("Error while matching regular expression %s: %s"),
1353 regex->pattern, match_error (info->matches));
1357 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1360 if (match_info != NULL)
1363 g_match_info_free (info);
1365 return info->matches >= 0;
1369 * g_regex_get_string_number:
1370 * @regex: #GRegex structure
1371 * @name: name of the subexpression
1373 * Retrieves the number of the subexpression named @name.
1375 * Returns: The number of the subexpression or -1 if @name
1381 g_regex_get_string_number (const GRegex *regex,
1386 g_return_val_if_fail (regex != NULL, -1);
1387 g_return_val_if_fail (name != NULL, -1);
1389 num = pcre_get_stringnumber (regex->pcre_re, name);
1390 if (num == PCRE_ERROR_NOSUBSTRING)
1397 * g_regex_split_simple:
1398 * @pattern: the regular expression
1399 * @string: the string to scan for matches
1400 * @compile_options: compile options for the regular expression
1401 * @match_options: match options
1403 * Breaks the string on the pattern, and returns an array of
1404 * the tokens. If the pattern contains capturing parentheses,
1405 * then the text for each of the substrings will also be returned.
1406 * If the pattern does not match anywhere in the string, then the
1407 * whole string is returned as the first token.
1409 * This function is equivalent to g_regex_split() but it does
1410 * not require to compile the pattern with g_regex_new(), avoiding
1411 * some lines of code when you need just to do a split without
1412 * extracting substrings, capture counts, and so on.
1414 * If this function is to be called on the same @pattern more than
1415 * once, it's more efficient to compile the pattern once with
1416 * g_regex_new() and then use g_regex_split().
1418 * As a special case, the result of splitting the empty string ""
1419 * is an empty vector, not a vector containing a single string.
1420 * The reason for this special case is that being able to represent
1421 * a empty vector is typically more useful than consistent handling
1422 * of empty elements. If you do need to represent empty elements,
1423 * you'll need to check for the empty string before calling this
1426 * A pattern that can match empty strings splits @string into
1427 * separate characters wherever it matches the empty string between
1428 * characters. For example splitting "ab c" using as a separator
1429 * "\s*", you will get "a", "b" and "c".
1431 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1436 g_regex_split_simple (const gchar *pattern,
1437 const gchar *string,
1438 GRegexCompileFlags compile_options,
1439 GRegexMatchFlags match_options)
1444 regex = g_regex_new (pattern, compile_options, 0, NULL);
1447 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1448 g_regex_unref (regex);
1454 * @regex: a #GRegex structure
1455 * @string: the string to split with the pattern
1456 * @match_options: match time option flags
1458 * Breaks the string on the pattern, and returns an array of the tokens.
1459 * If the pattern contains capturing parentheses, then the text for each
1460 * of the substrings will also be returned. If the pattern does not match
1461 * anywhere in the string, then the whole string is returned as the first
1464 * As a special case, the result of splitting the empty string "" is an
1465 * empty vector, not a vector containing a single string. The reason for
1466 * this special case is that being able to represent a empty vector is
1467 * typically more useful than consistent handling of empty elements. If
1468 * you do need to represent empty elements, you'll need to check for the
1469 * empty string before calling this function.
1471 * A pattern that can match empty strings splits @string into separate
1472 * characters wherever it matches the empty string between characters.
1473 * For example splitting "ab c" using as a separator "\s*", you will get
1476 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1481 g_regex_split (const GRegex *regex,
1482 const gchar *string,
1483 GRegexMatchFlags match_options)
1485 return g_regex_split_full (regex, string, -1, 0,
1486 match_options, 0, NULL);
1490 * g_regex_split_full:
1491 * @regex: a #GRegex structure
1492 * @string: the string to split with the pattern
1493 * @string_len: the length of @string, or -1 if @string is nul-terminated
1494 * @start_position: starting index of the string to match
1495 * @match_options: match time option flags
1496 * @max_tokens: the maximum number of tokens to split @string into.
1497 * If this is less than 1, the string is split completely
1498 * @error: return location for a #GError
1500 * Breaks the string on the pattern, and returns an array of the tokens.
1501 * If the pattern contains capturing parentheses, then the text for each
1502 * of the substrings will also be returned. If the pattern does not match
1503 * anywhere in the string, then the whole string is returned as the first
1506 * As a special case, the result of splitting the empty string "" is an
1507 * empty vector, not a vector containing a single string. The reason for
1508 * this special case is that being able to represent a empty vector is
1509 * typically more useful than consistent handling of empty elements. If
1510 * you do need to represent empty elements, you'll need to check for the
1511 * empty string before calling this function.
1513 * A pattern that can match empty strings splits @string into separate
1514 * characters wherever it matches the empty string between characters.
1515 * For example splitting "ab c" using as a separator "\s*", you will get
1518 * Setting @start_position differs from just passing over a shortened
1519 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1520 * that begins with any kind of lookbehind assertion, such as "\b".
1522 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1527 g_regex_split_full (const GRegex *regex,
1528 const gchar *string,
1530 gint start_position,
1531 GRegexMatchFlags match_options,
1535 GError *tmp_error = NULL;
1536 GMatchInfo *match_info;
1541 /* position of the last separator. */
1542 gint last_separator_end;
1543 /* was the last match 0 bytes long? */
1544 gboolean last_match_is_empty;
1545 /* the returned array of char **s */
1546 gchar **string_list;
1548 g_return_val_if_fail (regex != NULL, NULL);
1549 g_return_val_if_fail (string != NULL, NULL);
1550 g_return_val_if_fail (start_position >= 0, NULL);
1551 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1552 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1554 if (max_tokens <= 0)
1555 max_tokens = G_MAXINT;
1558 string_len = strlen (string);
1560 /* zero-length string */
1561 if (string_len - start_position == 0)
1562 return g_new0 (gchar *, 1);
1564 if (max_tokens == 1)
1566 string_list = g_new0 (gchar *, 2);
1567 string_list[0] = g_strndup (&string[start_position],
1568 string_len - start_position);
1574 last_separator_end = start_position;
1575 last_match_is_empty = FALSE;
1577 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1578 match_options, &match_info, &tmp_error);
1579 while (tmp_error == NULL)
1583 last_match_is_empty =
1584 (match_info->offsets[0] == match_info->offsets[1]);
1586 /* we need to skip empty separators at the same position of the end
1587 * of another separator. e.g. the string is "a b" and the separator
1588 * is " *", so from 1 to 2 we have a match and at position 2 we have
1589 * an empty match. */
1590 if (last_separator_end != match_info->offsets[1])
1595 token = g_strndup (string + last_separator_end,
1596 match_info->offsets[0] - last_separator_end);
1597 list = g_list_prepend (list, token);
1600 /* if there were substrings, these need to be added to
1602 match_count = g_match_info_get_match_count (match_info);
1603 if (match_count > 1)
1605 for (i = 1; i < match_count; i++)
1606 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1612 /* if there was no match, copy to end of string. */
1613 if (!last_match_is_empty)
1615 gchar *token = g_strndup (string + last_separator_end,
1616 match_info->string_len - last_separator_end);
1617 list = g_list_prepend (list, token);
1619 /* no more tokens, end the loop. */
1623 /* -1 to leave room for the last part. */
1624 if (token_count >= max_tokens - 1)
1626 /* we have reached the maximum number of tokens, so we copy
1627 * the remaining part of the string. */
1628 if (last_match_is_empty)
1630 /* the last match was empty, so we have moved one char
1631 * after the real position to avoid empty matches at the
1633 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1635 /* the if is needed in the case we have terminated the available
1636 * tokens, but we are at the end of the string, so there are no
1637 * characters left to copy. */
1638 if (string_len > match_info->pos)
1640 gchar *token = g_strndup (string + match_info->pos,
1641 string_len - match_info->pos);
1642 list = g_list_prepend (list, token);
1648 last_separator_end = match_info->pos;
1649 if (last_match_is_empty)
1650 /* if the last match was empty, g_match_info_next() has moved
1651 * forward to avoid infinite loops, but we still need to copy that
1653 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1655 match_ok = g_match_info_next (match_info, &tmp_error);
1657 g_match_info_free (match_info);
1658 if (tmp_error != NULL)
1660 g_propagate_error (error, tmp_error);
1661 g_list_foreach (list, (GFunc)g_free, NULL);
1663 match_info->pos = -1;
1667 string_list = g_new (gchar *, g_list_length (list) + 1);
1669 for (last = g_list_last (list); last; last = g_list_previous (last))
1670 string_list[i++] = last->data;
1680 REPL_TYPE_CHARACTER,
1681 REPL_TYPE_SYMBOLIC_REFERENCE,
1682 REPL_TYPE_NUMERIC_REFERENCE,
1683 REPL_TYPE_CHANGE_CASE
1688 CHANGE_CASE_NONE = 1 << 0,
1689 CHANGE_CASE_UPPER = 1 << 1,
1690 CHANGE_CASE_LOWER = 1 << 2,
1691 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1692 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1693 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1694 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1695 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1698 struct _InterpolationData
1704 ChangeCase change_case;
1708 free_interpolation_data (InterpolationData *data)
1710 g_free (data->text);
1714 static const gchar *
1715 expand_escape (const gchar *replacement,
1717 InterpolationData *data,
1722 const gchar *error_detail;
1724 GError *tmp_error = NULL;
1732 data->type = REPL_TYPE_CHARACTER;
1737 data->type = REPL_TYPE_CHARACTER;
1742 data->type = REPL_TYPE_CHARACTER;
1747 data->type = REPL_TYPE_CHARACTER;
1752 data->type = REPL_TYPE_CHARACTER;
1757 data->type = REPL_TYPE_CHARACTER;
1762 data->type = REPL_TYPE_CHARACTER;
1767 data->type = REPL_TYPE_CHARACTER;
1777 h = g_ascii_xdigit_value (*p);
1780 error_detail = _("hexadecimal digit or '}' expected");
1791 for (i = 0; i < 2; i++)
1793 h = g_ascii_xdigit_value (*p);
1796 error_detail = _("hexadecimal digit expected");
1803 data->type = REPL_TYPE_STRING;
1804 data->text = g_new0 (gchar, 8);
1805 g_unichar_to_utf8 (x, data->text);
1809 data->type = REPL_TYPE_CHANGE_CASE;
1810 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1814 data->type = REPL_TYPE_CHANGE_CASE;
1815 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1819 data->type = REPL_TYPE_CHANGE_CASE;
1820 data->change_case = CHANGE_CASE_LOWER;
1824 data->type = REPL_TYPE_CHANGE_CASE;
1825 data->change_case = CHANGE_CASE_UPPER;
1829 data->type = REPL_TYPE_CHANGE_CASE;
1830 data->change_case = CHANGE_CASE_NONE;
1836 error_detail = _("missing '<' in symbolic reference");
1845 error_detail = _("unfinished symbolic reference");
1852 error_detail = _("zero-length symbolic reference");
1855 if (g_ascii_isdigit (*q))
1860 h = g_ascii_digit_value (*q);
1863 error_detail = _("digit expected");
1872 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1879 if (!g_ascii_isalnum (*r))
1881 error_detail = _("illegal symbolic reference");
1888 data->text = g_strndup (q, p - q);
1889 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1894 /* if \0 is followed by a number is an octal number representing a
1895 * character, else it is a numeric reference. */
1896 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1899 p = g_utf8_next_char (p);
1912 for (i = 0; i < 3; i++)
1914 h = g_ascii_digit_value (*p);
1924 if (i == 2 && base == 10)
1930 if (base == 8 || i == 3)
1932 data->type = REPL_TYPE_STRING;
1933 data->text = g_new0 (gchar, 8);
1934 g_unichar_to_utf8 (x, data->text);
1938 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1943 error_detail = _("stray final '\\'");
1947 error_detail = _("unknown escape sequence");
1954 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1955 tmp_error = g_error_new (G_REGEX_ERROR,
1956 G_REGEX_ERROR_REPLACE,
1957 _("Error while parsing replacement "
1958 "text \"%s\" at char %lu: %s"),
1960 (gulong)(p - replacement),
1962 g_propagate_error (error, tmp_error);
1968 split_replacement (const gchar *replacement,
1972 InterpolationData *data;
1973 const gchar *p, *start;
1975 start = p = replacement;
1980 data = g_new0 (InterpolationData, 1);
1981 start = p = expand_escape (replacement, p, data, error);
1984 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1986 free_interpolation_data (data);
1990 list = g_list_prepend (list, data);
1995 if (*p == '\\' || *p == '\0')
1999 data = g_new0 (InterpolationData, 1);
2000 data->text = g_strndup (start, p - start);
2001 data->type = REPL_TYPE_STRING;
2002 list = g_list_prepend (list, data);
2008 return g_list_reverse (list);
2011 /* Change the case of c based on change_case. */
2012 #define CHANGE_CASE(c, change_case) \
2013 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2014 g_unichar_tolower (c) : \
2015 g_unichar_toupper (c))
2018 string_append (GString *string,
2020 ChangeCase *change_case)
2024 if (text[0] == '\0')
2027 if (*change_case == CHANGE_CASE_NONE)
2029 g_string_append (string, text);
2031 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2033 c = g_utf8_get_char (text);
2034 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2035 g_string_append (string, g_utf8_next_char (text));
2036 *change_case = CHANGE_CASE_NONE;
2040 while (*text != '\0')
2042 c = g_utf8_get_char (text);
2043 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2044 text = g_utf8_next_char (text);
2050 interpolate_replacement (const GMatchInfo *match_info,
2055 InterpolationData *idata;
2057 ChangeCase change_case = CHANGE_CASE_NONE;
2059 for (list = data; list; list = list->next)
2062 switch (idata->type)
2064 case REPL_TYPE_STRING:
2065 string_append (result, idata->text, &change_case);
2067 case REPL_TYPE_CHARACTER:
2068 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2069 if (change_case & CHANGE_CASE_SINGLE_MASK)
2070 change_case = CHANGE_CASE_NONE;
2072 case REPL_TYPE_NUMERIC_REFERENCE:
2073 match = g_match_info_fetch (match_info, idata->num);
2076 string_append (result, match, &change_case);
2080 case REPL_TYPE_SYMBOLIC_REFERENCE:
2081 match = g_match_info_fetch_named (match_info, idata->text);
2084 string_append (result, match, &change_case);
2088 case REPL_TYPE_CHANGE_CASE:
2089 change_case = idata->change_case;
2097 /* whether actual match_info is needed for replacement, i.e.
2098 * whether there are references
2101 interpolation_list_needs_match (GList *list)
2103 while (list != NULL)
2105 InterpolationData *data = list->data;
2107 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2108 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2121 * @regex: a #GRegex structure
2122 * @string: the string to perform matches against
2123 * @string_len: the length of @string, or -1 if @string is nul-terminated
2124 * @start_position: starting index of the string to match
2125 * @replacement: text to replace each match with
2126 * @match_options: options for the match
2127 * @error: location to store the error occuring, or %NULL to ignore errors
2129 * Replaces all occurances of the pattern in @regex with the
2130 * replacement text. Backreferences of the form '\number' or
2131 * '\g<number>' in the replacement text are interpolated by the
2132 * number-th captured subexpression of the match, '\g<name>' refers
2133 * to the captured subexpression with the given name. '\0' refers to the
2134 * complete match, but '\0' followed by a number is the octal representation
2135 * of a character. To include a literal '\' in the replacement, write '\\'.
2136 * There are also escapes that changes the case of the following text:
2139 * <varlistentry><term>\l</term>
2141 * <para>Convert to lower case the next character</para>
2144 * <varlistentry><term>\u</term>
2146 * <para>Convert to upper case the next character</para>
2149 * <varlistentry><term>\L</term>
2151 * <para>Convert to lower case till \E</para>
2154 * <varlistentry><term>\U</term>
2156 * <para>Convert to upper case till \E</para>
2159 * <varlistentry><term>\E</term>
2161 * <para>End case modification</para>
2166 * If you do not need to use backreferences use g_regex_replace_literal().
2168 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2169 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2170 * you can use g_regex_replace_literal().
2172 * Setting @start_position differs from just passing over a shortened
2173 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2174 * begins with any kind of lookbehind assertion, such as "\b".
2176 * Returns: a newly allocated string containing the replacements
2181 g_regex_replace (const GRegex *regex,
2182 const gchar *string,
2184 gint start_position,
2185 const gchar *replacement,
2186 GRegexMatchFlags match_options,
2191 GError *tmp_error = NULL;
2193 g_return_val_if_fail (regex != NULL, NULL);
2194 g_return_val_if_fail (string != NULL, NULL);
2195 g_return_val_if_fail (start_position >= 0, NULL);
2196 g_return_val_if_fail (replacement != NULL, NULL);
2197 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2198 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2200 list = split_replacement (replacement, &tmp_error);
2201 if (tmp_error != NULL)
2203 g_propagate_error (error, tmp_error);
2207 result = g_regex_replace_eval (regex,
2208 string, string_len, start_position,
2210 interpolate_replacement,
2213 if (tmp_error != NULL)
2214 g_propagate_error (error, tmp_error);
2216 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2223 literal_replacement (const GMatchInfo *match_info,
2227 g_string_append (result, data);
2232 * g_regex_replace_literal:
2233 * @regex: a #GRegex structure
2234 * @string: the string to perform matches against
2235 * @string_len: the length of @string, or -1 if @string is nul-terminated
2236 * @start_position: starting index of the string to match
2237 * @replacement: text to replace each match with
2238 * @match_options: options for the match
2239 * @error: location to store the error occuring, or %NULL to ignore errors
2241 * Replaces all occurances of the pattern in @regex with the
2242 * replacement text. @replacement is replaced literally, to
2243 * include backreferences use g_regex_replace().
2245 * Setting @start_position differs from just passing over a
2246 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2247 * case of a pattern that begins with any kind of lookbehind
2248 * assertion, such as "\b".
2250 * Returns: a newly allocated string containing the replacements
2255 g_regex_replace_literal (const GRegex *regex,
2256 const gchar *string,
2258 gint start_position,
2259 const gchar *replacement,
2260 GRegexMatchFlags match_options,
2263 g_return_val_if_fail (replacement != NULL, NULL);
2264 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2266 return g_regex_replace_eval (regex,
2267 string, string_len, start_position,
2269 literal_replacement,
2270 (gpointer)replacement,
2275 * g_regex_replace_eval:
2276 * @regex: a #GRegex structure from g_regex_new()
2277 * @string: string to perform matches against
2278 * @string_len: the length of @string, or -1 if @string is nul-terminated
2279 * @start_position: starting index of the string to match
2280 * @match_options: options for the match
2281 * @eval: a function to call for each match
2282 * @user_data: user data to pass to the function
2283 * @error: location to store the error occuring, or %NULL to ignore errors
2285 * Replaces occurances of the pattern in regex with the output of
2286 * @eval for that occurance.
2288 * Setting @start_position differs from just passing over a shortened
2289 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2290 * that begins with any kind of lookbehind assertion, such as "\b".
2292 * Returns: a newly allocated string containing the replacements
2297 g_regex_replace_eval (const GRegex *regex,
2298 const gchar *string,
2300 gint start_position,
2301 GRegexMatchFlags match_options,
2302 GRegexEvalCallback eval,
2306 GMatchInfo *match_info;
2309 gboolean done = FALSE;
2310 GError *tmp_error = NULL;
2312 g_return_val_if_fail (regex != NULL, NULL);
2313 g_return_val_if_fail (string != NULL, NULL);
2314 g_return_val_if_fail (start_position >= 0, NULL);
2315 g_return_val_if_fail (eval != NULL, NULL);
2316 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2319 string_len = strlen (string);
2321 result = g_string_sized_new (string_len);
2323 /* run down the string making matches. */
2324 g_regex_match_full (regex, string, string_len, start_position,
2325 match_options, &match_info, &tmp_error);
2326 while (!done && g_match_info_matches (match_info))
2328 g_string_append_len (result,
2330 match_info->offsets[0] - str_pos);
2331 done = (*eval) (match_info, result, user_data);
2332 str_pos = match_info->offsets[1];
2333 g_match_info_next (match_info, &tmp_error);
2335 g_match_info_free (match_info);
2336 if (tmp_error != NULL)
2338 g_propagate_error (error, tmp_error);
2339 g_string_free (result, TRUE);
2343 g_string_append_len (result, string + str_pos, string_len - str_pos);
2344 return g_string_free (result, FALSE);
2348 * g_regex_check_replacement:
2349 * @replacement: the replacement string
2350 * @has_references: location to store information about
2351 * references in @replacement or %NULL
2352 * @error: location to store error
2354 * Checks whether @replacement is a valid replacement string
2355 * (see g_regex_replace()), i.e. that all escape sequences in
2358 * If @has_references is not %NULL then @replacement is checked
2359 * for pattern references. For instance, replacement text 'foo\n'
2360 * does not contain references and may be evaluated without information
2361 * about actual match, but '\0\1' (whole match followed by first
2362 * subpattern) requires valid #GMatchInfo object.
2364 * Returns: whether @replacement is a valid replacement string
2369 g_regex_check_replacement (const gchar *replacement,
2370 gboolean *has_references,
2376 list = split_replacement (replacement, &tmp);
2380 g_propagate_error (error, tmp);
2385 *has_references = interpolation_list_needs_match (list);
2387 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2394 * g_regex_escape_string:
2395 * @string: the string to escape
2396 * @length: the length of @string, or -1 if @string is nul-terminated
2398 * Escapes the special characters used for regular expressions
2399 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2400 * function is useful to dynamically generate regular expressions.
2402 * @string can contain nul characters that are replaced with "\0",
2403 * in this case remember to specify the correct length of @string
2406 * Returns: a newly-allocated escaped string
2411 g_regex_escape_string (const gchar *string,
2415 const char *p, *piece_start, *end;
2417 g_return_val_if_fail (string != NULL, NULL);
2420 length = strlen (string);
2422 end = string + length;
2423 p = piece_start = string;
2424 escaped = g_string_sized_new (length + 1);
2445 if (p != piece_start)
2446 /* copy the previous piece. */
2447 g_string_append_len (escaped, piece_start, p - piece_start);
2448 g_string_append_c (escaped, '\\');
2450 g_string_append_c (escaped, '0');
2452 g_string_append_c (escaped, *p);
2456 p = g_utf8_next_char (p);
2461 if (piece_start < end)
2462 g_string_append_len (escaped, piece_start, end - piece_start);
2464 return g_string_free (escaped, FALSE);
2467 #define __G_REGEX_C__
2468 #include "galiasdef.c"