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 match_info->matches = pcre_exec (match_info->regex->pcre_re,
304 match_info->regex->extra,
306 match_info->string_len,
308 match_info->regex->match_opts |
309 match_info->match_opts,
311 match_info->n_offsets);
312 if (IS_PCRE_ERROR (match_info->matches))
314 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
315 _("Error while matching regular expression %s: %s"),
316 match_info->regex->pattern, match_error (match_info->matches));
320 /* avoid infinite loops if the pattern is an empty string or something
322 if (match_info->pos == match_info->offsets[1])
324 if (match_info->pos > match_info->string_len)
326 /* we have reached the end of the string */
327 match_info->pos = -1;
328 match_info->matches = PCRE_ERROR_NOMATCH;
331 match_info->pos = NEXT_CHAR (match_info->regex,
332 &match_info->string[match_info->pos]) -
337 match_info->pos = match_info->offsets[1];
340 return match_info->matches >= 0;
344 * g_match_info_matches:
345 * @match_info: a #GMatchInfo structure
347 * Returns: %TRUE if the previous match operation succeeded, %FALSE
353 g_match_info_matches (const GMatchInfo *match_info)
355 g_return_val_if_fail (match_info != NULL, FALSE);
357 return match_info->matches >= 0;
361 * g_match_info_get_match_count:
362 * @match_info: a #GMatchInfo structure
364 * Retrieves the number of matched substrings (including substring 0, that
365 * is the whole matched text), so 1 is returned if the pattern has no
366 * substrings in it and 0 is returned if the match failed.
368 * If the last match was obtained using the DFA algorithm, that is using
369 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
370 * count is not that of the number of capturing parentheses but that of
371 * the number of matched substrings.
373 * Returns: Number of matched substrings, or -1 if an error occurred
378 g_match_info_get_match_count (const GMatchInfo *match_info)
380 g_return_val_if_fail (match_info, -1);
382 if (match_info->matches == PCRE_ERROR_NOMATCH)
385 else if (match_info->matches < PCRE_ERROR_NOMATCH)
390 return match_info->matches;
394 * g_match_info_is_partial_match:
395 * @match_info: a #GMatchInfo structure
397 * Usually if the string passed to g_regex_match*() matches as far as
398 * it goes, but is too short to match the entire pattern, %FALSE is
399 * returned. There are circumstances where it might be helpful to
400 * distinguish this case from other cases in which there is no match.
402 * Consider, for example, an application where a human is required to
403 * type in data for a field with specific formatting requirements. An
404 * example might be a date in the form ddmmmyy, defined by the pattern
405 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
406 * If the application sees the user’s keystrokes one by one, and can
407 * check that what has been typed so far is potentially valid, it is
408 * able to raise an error as soon as a mistake is made.
410 * GRegex supports the concept of partial matching by means of the
411 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
412 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
413 * for a complete match, %FALSE otherwise. But, when this functions
414 * returns %FALSE, you can check if the match was partial calling
415 * g_match_info_is_partial_match().
417 * When using partial matching you cannot use g_match_info_fetch*().
419 * Because of the way certain internal optimizations are implemented the
420 * partial matching algorithm cannot be used with all patterns. So repeated
421 * single characters such as "a{2,4}" and repeated single metasequences such
422 * as "\d+" are not permitted if the maximum number of occurrences is
423 * greater than one. Optional items such as "\d?" (where the maximum is one)
424 * are permitted. Quantifiers with any values are permitted after
425 * parentheses, so the invalid examples above can be coded thus "(a){2,4}"
426 * and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set for a pattern that does
427 * not conform to the restrictions, matching functions return an error.
429 * Returns: %TRUE if the match was partial, %FALSE otherwise
434 g_match_info_is_partial_match (const GMatchInfo *match_info)
436 g_return_val_if_fail (match_info != NULL, FALSE);
438 return match_info->matches == PCRE_ERROR_PARTIAL;
442 * g_match_info_expand_references:
443 * @match_info: a #GMatchInfo or %NULL
444 * @string_to_expand: the string to expand
445 * @error: location to store the error occuring, or %NULL to ignore errors
447 * Returns a new string containing the text in @string_to_expand with
448 * references and escape sequences expanded. References refer to the last
449 * match done with @string against @regex and have the same syntax used by
452 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
453 * passed to g_regex_new().
455 * The backreferences are extracted from the string passed to the match
456 * function, so you cannot call this function after freeing the string.
458 * @match_info may be %NULL in which case @string_to_expand must not
459 * contain references. For instance "foo\n" does not refer to an actual
460 * pattern and '\n' merely will be replaced with \n character,
461 * while to expand "\0" (whole match) one needs the result of a match.
462 * Use g_regex_check_replacement() to find out whether @string_to_expand
463 * contains references.
465 * Returns: the expanded string, or %NULL if an error occurred
470 g_match_info_expand_references (const GMatchInfo *match_info,
471 const gchar *string_to_expand,
476 GError *tmp_error = NULL;
478 g_return_val_if_fail (string_to_expand != NULL, NULL);
479 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
481 list = split_replacement (string_to_expand, &tmp_error);
482 if (tmp_error != NULL)
484 g_propagate_error (error, tmp_error);
488 if (!match_info && interpolation_list_needs_match (list))
490 g_critical ("String '%s' contains references to the match, can't "
491 "expand references without GMatchInfo object",
496 result = g_string_sized_new (strlen (string_to_expand));
497 interpolate_replacement (match_info, result, list);
499 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
502 return g_string_free (result, FALSE);
506 * g_match_info_fetch:
507 * @match_info: #GMatchInfo structure
508 * @match_num: number of the sub expression
510 * Retrieves the text matching the @match_num<!-- -->'th capturing parentheses.
511 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
514 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
515 * sub pattern 1, matching "b" against "(a)?b") then an empty string is
518 * If the match was obtained using the DFA algorithm, that is using
519 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
520 * string is not that of a set of parentheses but that of a matched
521 * substring. Substrings are matched in reverse order of length, so 0 is
524 * The string is fetched from the string passed to the match function,
525 * so you cannot call this function after freeing the string.
527 * Returns: The matched substring, or %NULL if an error occurred.
528 * You have to free the string yourself
533 g_match_info_fetch (const GMatchInfo *match_info,
536 /* we cannot use pcre_get_substring() because it allocates the
537 * string using pcre_malloc(). */
541 g_return_val_if_fail (match_info != NULL, NULL);
542 g_return_val_if_fail (match_num >= 0, NULL);
544 /* match_num does not exist or it didn't matched, i.e. matching "b"
545 * against "(a)?b" then group 0 is empty. */
546 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
548 else if (start == -1)
549 match = g_strdup ("");
551 match = g_strndup (&match_info->string[start], end - start);
557 * g_match_info_fetch_pos:
558 * @match_info: #GMatchInfo structure
559 * @match_num: number of the sub expression
560 * @start_pos: pointer to location where to store the start position
561 * @end_pos: pointer to location where to store the end position
563 * Retrieves the position of the @match_num<!-- -->'th capturing parentheses.
564 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
567 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
568 * sub pattern 1, matching "b" against "(a)?b") then @start_pos and @end_pos
569 * are set to -1 and %TRUE is returned.
571 * If the match was obtained using the DFA algorithm, that is using
572 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
573 * position is not that of a set of parentheses but that of a matched
574 * substring. Substrings are matched in reverse order of length, so 0 is
577 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
578 * position cannot be fetched, @start_pos and @end_pos are left
584 g_match_info_fetch_pos (const GMatchInfo *match_info,
589 g_return_val_if_fail (match_info != NULL, FALSE);
590 g_return_val_if_fail (match_num >= 0, FALSE);
592 /* make sure the sub expression number they're requesting is less than
593 * the total number of sub expressions that were matched. */
594 if (match_num >= match_info->matches)
597 if (start_pos != NULL)
598 *start_pos = match_info->offsets[2 * match_num];
601 *end_pos = match_info->offsets[2 * match_num + 1];
607 * Returns number of first matched subpattern with name @name.
608 * There may be more than one in case when DUPNAMES is used,
609 * and not all subpatterns with that name match;
610 * pcre_get_stringnumber() does not work in that case.
613 get_matched_substring_number (const GMatchInfo *match_info,
621 * FIXME: (?J) may be used inside the pattern as the equivalent of
622 * DUPNAMES compile option. In this case we can't know about it,
623 * and pcre doesn't tell us about it either, it uses private flag
624 * PCRE_JCHANGED for this. So we have to always search string
625 * table, unlike pcre which uses pcre_get_stringnumber() shortcut
626 * when possible. It shouldn't be actually bad since
627 * pcre_get_stringtable_entries() uses binary search; still would
628 * be better to fix it, to be not worse than pcre.
631 if ((match_info->regex->compile_opts & G_REGEX_DUPNAMES) == 0)
632 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
635 /* This code is copied from pcre_get.c: get_first_set() */
636 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
644 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
646 gint n = (entry[0] << 8) + entry[1];
647 if (match_info->offsets[n*2] >= 0)
651 return (first[0] << 8) + first[1];
655 * g_match_info_fetch_named:
656 * @match_info: #GMatchInfo structure
657 * @name: name of the subexpression
659 * Retrieves the text matching the capturing parentheses named @name.
661 * If @name is a valid sub pattern name but it didn't match anything (e.g.
662 * sub pattern "X", matching "b" against "(?P<X>a)?b") then an empty
663 * string is returned.
665 * The string is fetched from the string passed to the match function,
666 * so you cannot call this function after freeing the string.
668 * Returns: The matched substring, or %NULL if an error occurred.
669 * You have to free the string yourself
674 g_match_info_fetch_named (const GMatchInfo *match_info,
677 /* we cannot use pcre_get_named_substring() because it allocates the
678 * string using pcre_malloc(). */
681 g_return_val_if_fail (match_info != NULL, NULL);
682 g_return_val_if_fail (name != NULL, NULL);
684 num = get_matched_substring_number (match_info, name);
688 return g_match_info_fetch (match_info, num);
692 * g_match_info_fetch_named_pos:
693 * @match_info: #GMatchInfo structure
694 * @name: name of the subexpression
695 * @start_pos: pointer to location where to store the start position
696 * @end_pos: pointer to location where to store the end position
698 * Retrieves the position of the capturing parentheses named @name.
700 * If @name is a valid sub pattern name but it didn't match anything (e.g.
701 * sub pattern "X", matching "b" against "(?P<X>a)?b") then @start_pos and
702 * @end_pos are set to -1 and %TRUE is returned.
704 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
705 * position cannot be fetched, @start_pos and @end_pos are left
711 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
718 g_return_val_if_fail (match_info != NULL, FALSE);
719 g_return_val_if_fail (name != NULL, FALSE);
721 num = get_matched_substring_number (match_info, name);
725 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
729 * g_match_info_fetch_all:
730 * @match_info: a #GMatchInfo structure
732 * Bundles up pointers to each of the matching substrings from a match
733 * and stores them in an array of gchar pointers. The first element in
734 * the returned array is the match number 0, i.e. the entire matched
737 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
738 * "b" against "(a)?b") then an empty string is inserted.
740 * If the last match was obtained using the DFA algorithm, that is using
741 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
742 * strings are not that matched by sets of parentheses but that of the
743 * matched substring. Substrings are matched in reverse order of length,
744 * so the first one is the longest match.
746 * The strings are fetched from the string passed to the match function,
747 * so you cannot call this function after freeing the string.
749 * Returns: a %NULL-terminated array of gchar * pointers. It must be freed
750 * using g_strfreev(). If the previous match failed %NULL is
756 g_match_info_fetch_all (const GMatchInfo *match_info)
758 /* we cannot use pcre_get_substring_list() because the returned value
759 * isn't suitable for g_strfreev(). */
763 g_return_val_if_fail (match_info != NULL, FALSE);
765 if (match_info->matches < 0)
768 result = g_new (gchar *, match_info->matches + 1);
769 for (i = 0; i < match_info->matches; i++)
770 result[i] = g_match_info_fetch (match_info, i);
780 g_regex_error_quark (void)
782 static GQuark error_quark = 0;
784 if (error_quark == 0)
785 error_quark = g_quark_from_static_string ("g-regex-error-quark");
794 * Increases reference count of @regex by 1.
801 g_regex_ref (GRegex *regex)
803 g_return_val_if_fail (regex != NULL, NULL);
804 g_atomic_int_inc ((gint*) ®ex->ref_count);
812 * Decreases reference count of @regex by 1. When reference count drops
813 * to zero, it frees all the memory associated with the regex structure.
818 g_regex_unref (GRegex *regex)
820 g_return_if_fail (regex != NULL);
822 if (g_atomic_int_exchange_and_add ((gint *) ®ex->ref_count, -1) - 1 == 0)
824 g_free (regex->pattern);
825 if (regex->pcre_re != NULL)
826 pcre_free (regex->pcre_re);
827 if (regex->extra != NULL)
828 pcre_free (regex->extra);
835 * @pattern: the regular expression
836 * @compile_options: compile options for the regular expression
837 * @match_options: match options for the regular expression
838 * @error: return location for a #GError
840 * Compiles the regular expression to an internal form, and does the initial
841 * setup of the #GRegex structure.
843 * Returns: a #GRegex structure. Call g_regex_unref() when you are done
849 g_regex_new (const gchar *pattern,
850 GRegexCompileFlags compile_options,
851 GRegexMatchFlags match_options,
858 gboolean optimize = FALSE;
859 static gboolean initialized = FALSE;
861 g_return_val_if_fail (pattern != NULL, NULL);
862 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
863 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
864 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
871 pcre_config (PCRE_CONFIG_UTF8, &support);
874 msg = N_("PCRE library is compiled without UTF8 support");
876 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
880 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
883 msg = N_("PCRE library is compiled without UTF8 properties support");
885 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
892 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
893 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
894 if (compile_options & G_REGEX_OPTIMIZE)
897 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
898 * instead uses UTF-8 only if required with PCRE_UTF8. */
899 if (compile_options & G_REGEX_RAW)
902 compile_options &= ~G_REGEX_RAW;
907 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
908 match_options |= PCRE_NO_UTF8_CHECK;
911 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
912 * not for the system one. */
913 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
914 !(compile_options & G_REGEX_NEWLINE_LF))
916 compile_options |= PCRE_NEWLINE_ANY;
919 /* compile the pattern */
920 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
922 /* if the compilation failed, set the error member and return
926 GError *tmp_error = g_error_new (G_REGEX_ERROR,
927 G_REGEX_ERROR_COMPILE,
928 _("Error while compiling regular "
929 "expression %s at char %d: %s"),
930 pattern, erroffset, errmsg);
931 g_propagate_error (error, tmp_error);
936 regex = g_new0 (GRegex, 1);
937 regex->ref_count = 1;
938 regex->pattern = g_strdup (pattern);
940 regex->compile_opts = compile_options;
941 regex->match_opts = match_options;
945 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
948 GError *tmp_error = g_error_new (G_REGEX_ERROR,
949 G_REGEX_ERROR_OPTIMIZE,
950 _("Error while optimizing "
951 "regular expression %s: %s"),
954 g_propagate_error (error, tmp_error);
963 * g_regex_get_pattern:
964 * @regex: a #GRegex structure
966 * Gets the pattern string associated with @regex, i.e. a copy of
967 * the string passed to g_regex_new().
969 * Returns: the pattern of @regex
974 g_regex_get_pattern (const GRegex *regex)
976 g_return_val_if_fail (regex != NULL, NULL);
978 return regex->pattern;
982 * g_regex_get_max_backref:
985 * Returns the number of the highest back reference
986 * in the pattern, or 0 if the pattern does not contain
989 * Returns: the number of the highest back reference.
994 g_regex_get_max_backref (const GRegex *regex)
998 pcre_fullinfo (regex->pcre_re, regex->extra,
999 PCRE_INFO_BACKREFMAX, &value);
1005 * g_regex_get_capture_count:
1008 * Returns the number of capturing subpatterns in the pattern.
1010 * Returns: the number of capturing subpatterns.
1015 g_regex_get_capture_count (const GRegex *regex)
1019 pcre_fullinfo (regex->pcre_re, regex->extra,
1020 PCRE_INFO_CAPTURECOUNT, &value);
1026 * g_regex_match_simple:
1027 * @pattern: the regular expression
1028 * @string: the string to scan for matches
1029 * @compile_options: compile options for the regular expression
1030 * @match_options: match options
1032 * Scans for a match in @string for @pattern.
1034 * This function is equivalent to g_regex_match() but it does not
1035 * require to compile the pattern with g_regex_new(), avoiding some
1036 * lines of code when you need just to do a match without extracting
1037 * substrings, capture counts, and so on.
1039 * If this function is to be called on the same @pattern more than
1040 * once, it's more efficient to compile the pattern once with
1041 * g_regex_new() and then use g_regex_match().
1043 * Returns: %TRUE is the string matched, %FALSE otherwise
1048 g_regex_match_simple (const gchar *pattern,
1049 const gchar *string,
1050 GRegexCompileFlags compile_options,
1051 GRegexMatchFlags match_options)
1056 regex = g_regex_new (pattern, compile_options, 0, NULL);
1059 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1060 g_regex_unref (regex);
1066 * @regex: a #GRegex structure from g_regex_new()
1067 * @string: the string to scan for matches
1068 * @match_options: match options
1069 * @match_info: pointer to location where to store the #GMatchInfo, or
1070 * %NULL if you do not need it
1072 * Scans for a match in string for the pattern in @regex. The @match_options
1073 * are combined with the match options specified when the @regex structure
1074 * was created, letting you have more flexibility in reusing #GRegex
1077 * A #GMatchInfo structure, used to get information on the match, is stored
1078 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1079 * it is created even if the function returns %FALSE, i.e. you must free it
1080 * regardless if regular expression actually matched.
1082 * To retrieve all the non-overlapping matches of the pattern in string you
1083 * can use g_match_info_next().
1085 * <informalexample><programlisting>
1087 * print_uppercase_words (const gchar *string)
1089 * /* Print all uppercase-only words. */
1091 * GMatchInfo *match_info;
1093 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1094 * g_regex_match (regex, string, 0, &match_info);
1095 * while (g_match_info_matches (match_info))
1097 * gchar *word = g_match_info_fetch (match_info, 0);
1098 * g_print ("Found: %s\n", word);
1100 * g_match_info_next (match_info, NULL);
1102 * g_match_info_free (match_info);
1103 * g_regex_unref (regex);
1105 * </programlisting></informalexample>
1107 * Returns: %TRUE is the string matched, %FALSE otherwise
1112 g_regex_match (const GRegex *regex,
1113 const gchar *string,
1114 GRegexMatchFlags match_options,
1115 GMatchInfo **match_info)
1117 return g_regex_match_full (regex, string, -1, 0, match_options,
1122 * g_regex_match_full:
1123 * @regex: a #GRegex structure from g_regex_new()
1124 * @string: the string to scan for matches
1125 * @string_len: the length of @string, or -1 if @string is nul-terminated
1126 * @start_position: starting index of the string to match
1127 * @match_options: match options
1128 * @match_info: pointer to location where to store the #GMatchInfo, or
1129 * %NULL if you do not need it
1130 * @error: location to store the error occuring, or %NULL to ignore errors
1132 * Scans for a match in string for the pattern in @regex. The @match_options
1133 * are combined with the match options specified when the @regex structure
1134 * was created, letting you have more flexibility in reusing #GRegex
1137 * Setting @start_position differs from just passing over a shortened string
1138 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1139 * with any kind of lookbehind assertion, such as "\b".
1141 * A #GMatchInfo structure, used to get information on the match, is stored
1142 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1143 * it is created even if the function returns %FALSE, i.e. you must free it
1144 * regardless if regular expression actually matched.
1146 * @string is not copied and is used in #GMatchInfo internally. If you use
1147 * any #GMatchInfo method (except g_match_info_free()) after freeing or
1148 * modifying @string then the behaviour is undefined.
1150 * To retrieve all the non-overlapping matches of the pattern in string you
1151 * can use g_match_info_next().
1153 * <informalexample><programlisting>
1155 * print_uppercase_words (const gchar *string)
1157 * /* Print all uppercase-only words. */
1159 * GMatchInfo *match_info;
1160 * GError *error = NULL;
1162 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1163 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1164 * while (g_match_info_matches (match_info))
1166 * gchar *word = g_match_info_fetch (match_info, 0);
1167 * g_print ("Found: %s\n", word);
1169 * g_match_info_next (match_info, &error);
1171 * g_match_info_free (match_info);
1172 * g_regex_unref (regex);
1173 * if (error != NULL)
1175 * g_printerr ("Error while matching: %s\n", error->message);
1176 * g_error_free (error);
1179 * </programlisting></informalexample>
1181 * Returns: %TRUE is the string matched, %FALSE otherwise
1186 g_regex_match_full (const GRegex *regex,
1187 const gchar *string,
1189 gint start_position,
1190 GRegexMatchFlags match_options,
1191 GMatchInfo **match_info,
1197 g_return_val_if_fail (regex != NULL, FALSE);
1198 g_return_val_if_fail (string != NULL, FALSE);
1199 g_return_val_if_fail (start_position >= 0, FALSE);
1200 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1201 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1203 info = match_info_new (regex, string, string_len, start_position,
1204 match_options, FALSE);
1205 match_ok = g_match_info_next (info, error);
1206 if (match_info != NULL)
1209 g_match_info_free (info);
1215 * g_regex_match_all:
1216 * @regex: a #GRegex structure from g_regex_new()
1217 * @string: the string to scan for matches
1218 * @match_options: match options
1219 * @match_info: pointer to location where to store the #GMatchInfo, or
1220 * %NULL if you do not need it
1222 * Using the standard algorithm for regular expression matching only the
1223 * longest match in the string is retrieved. This function uses a
1224 * different algorithm so it can retrieve all the possible matches.
1225 * For more documentation see g_regex_match_all_full().
1227 * A #GMatchInfo structure, used to get information on the match, is stored
1228 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1229 * it is created even if the function returns %FALSE, i.e. you must free it
1230 * regardless if regular expression actually matched.
1232 * Returns: %TRUE is the string matched, %FALSE otherwise
1237 g_regex_match_all (const GRegex *regex,
1238 const gchar *string,
1239 GRegexMatchFlags match_options,
1240 GMatchInfo **match_info)
1242 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1247 * g_regex_match_all_full:
1248 * @regex: a #GRegex structure from g_regex_new()
1249 * @string: the string to scan for matches
1250 * @string_len: the length of @string, or -1 if @string is nul-terminated
1251 * @start_position: starting index of the string to match
1252 * @match_options: match options
1253 * @match_info: pointer to location where to store the #GMatchInfo, or
1254 * %NULL if you do not need it
1255 * @error: location to store the error occuring, or %NULL to ignore errors
1257 * Using the standard algorithm for regular expression matching only the
1258 * longest match in the string is retrieved, it is not possibile to obtain
1259 * all the available matches. For instance matching
1260 * "<a> <b> <c>" against the pattern "<.*>" you get
1261 * "<a> <b> <c>".
1263 * This function uses a different algorithm (called DFA, i.e. deterministic
1264 * finite automaton), so it can retrieve all the possible matches, all
1265 * starting at the same point in the string. For instance matching
1266 * "<a> <b> <c>" against the pattern "<.*>" you
1267 * would obtain three matches: "<a> <b> <c>",
1268 * "<a> <b>" and "<a>".
1270 * The number of matched strings is retrieved using
1271 * g_match_info_get_match_count().
1272 * To obtain the matched strings and their position you can use,
1273 * respectively, g_match_info_fetch() and g_match_info_fetch_pos(). Note that
1274 * the strings are returned in reverse order of length; that is, the longest
1275 * matching string is given first.
1277 * Note that the DFA algorithm is slower than the standard one and it is not
1278 * able to capture substrings, so backreferences do not work.
1280 * Setting @start_position differs from just passing over a shortened string
1281 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1282 * with any kind of lookbehind assertion, such as "\b".
1284 * A #GMatchInfo structure, used to get information on the match, is stored
1285 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1286 * it is created even if the function returns %FALSE, i.e. you must free it
1287 * regardless if regular expression actually matched.
1289 * Returns: %TRUE is the string matched, %FALSE otherwise
1294 g_regex_match_all_full (const GRegex *regex,
1295 const gchar *string,
1297 gint start_position,
1298 GRegexMatchFlags match_options,
1299 GMatchInfo **match_info,
1305 g_return_val_if_fail (regex != NULL, FALSE);
1306 g_return_val_if_fail (string != NULL, FALSE);
1307 g_return_val_if_fail (start_position >= 0, FALSE);
1308 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1309 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1311 info = match_info_new (regex, string, string_len, start_position,
1312 match_options, TRUE);
1318 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1319 info->string, info->string_len,
1321 regex->match_opts | match_options,
1322 info->offsets, info->n_offsets,
1323 info->workspace, info->n_workspace);
1324 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1326 /* info->workspace is too small. */
1327 info->n_workspace *= 2;
1328 info->workspace = g_realloc (info->workspace,
1329 info->n_workspace * sizeof (gint));
1332 else if (info->matches == 0)
1334 /* info->offsets is too small. */
1335 info->n_offsets *= 2;
1336 info->offsets = g_realloc (info->offsets,
1337 info->n_offsets * sizeof (gint));
1340 else if (IS_PCRE_ERROR (info->matches))
1342 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1343 _("Error while matching regular expression %s: %s"),
1344 regex->pattern, match_error (info->matches));
1348 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1351 if (match_info != NULL)
1354 g_match_info_free (info);
1356 return info->matches >= 0;
1360 * g_regex_get_string_number:
1361 * @regex: #GRegex structure
1362 * @name: name of the subexpression
1364 * Retrieves the number of the subexpression named @name.
1366 * Returns: The number of the subexpression or -1 if @name does not exists
1371 g_regex_get_string_number (const GRegex *regex,
1376 g_return_val_if_fail (regex != NULL, -1);
1377 g_return_val_if_fail (name != NULL, -1);
1379 num = pcre_get_stringnumber (regex->pcre_re, name);
1380 if (num == PCRE_ERROR_NOSUBSTRING)
1387 * g_regex_split_simple:
1388 * @pattern: the regular expression
1389 * @string: the string to scan for matches
1390 * @compile_options: compile options for the regular expression
1391 * @match_options: match options
1393 * Breaks the string on the pattern, and returns an array of the tokens.
1394 * If the pattern contains capturing parentheses, then the text for each
1395 * of the substrings will also be returned. If the pattern does not match
1396 * anywhere in the string, then the whole string is returned as the first
1399 * This function is equivalent to g_regex_split() but it does not
1400 * require to compile the pattern with g_regex_new(), avoiding some
1401 * lines of code when you need just to do a split without extracting
1402 * substrings, capture counts, and so on.
1404 * If this function is to be called on the same @pattern more than
1405 * once, it's more efficient to compile the pattern once with
1406 * g_regex_new() and then use g_regex_split().
1408 * As a special case, the result of splitting the empty string "" is an
1409 * empty vector, not a vector containing a single string. The reason for
1410 * this special case is that being able to represent a empty vector is
1411 * typically more useful than consistent handling of empty elements. If
1412 * you do need to represent empty elements, you'll need to check for the
1413 * empty string before calling this function.
1415 * A pattern that can match empty strings splits @string into separate
1416 * characters wherever it matches the empty string between characters.
1417 * For example splitting "ab c" using as a separator "\s*", you will get
1420 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1425 g_regex_split_simple (const gchar *pattern,
1426 const gchar *string,
1427 GRegexCompileFlags compile_options,
1428 GRegexMatchFlags match_options)
1433 regex = g_regex_new (pattern, compile_options, 0, NULL);
1436 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1437 g_regex_unref (regex);
1443 * @regex: a #GRegex structure
1444 * @string: the string to split with the pattern
1445 * @match_options: match time option flags
1447 * Breaks the string on the pattern, and returns an array of the tokens.
1448 * If the pattern contains capturing parentheses, then the text for each
1449 * of the substrings will also be returned. If the pattern does not match
1450 * anywhere in the string, then the whole string is returned as the first
1453 * As a special case, the result of splitting the empty string "" is an
1454 * empty vector, not a vector containing a single string. The reason for
1455 * this special case is that being able to represent a empty vector is
1456 * typically more useful than consistent handling of empty elements. If
1457 * you do need to represent empty elements, you'll need to check for the
1458 * empty string before calling this function.
1460 * A pattern that can match empty strings splits @string into separate
1461 * characters wherever it matches the empty string between characters.
1462 * For example splitting "ab c" using as a separator "\s*", you will get
1465 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1470 g_regex_split (const GRegex *regex,
1471 const gchar *string,
1472 GRegexMatchFlags match_options)
1474 return g_regex_split_full (regex, string, -1, 0,
1475 match_options, 0, NULL);
1479 * g_regex_split_full:
1480 * @regex: a #GRegex structure
1481 * @string: the string to split with the pattern
1482 * @string_len: the length of @string, or -1 if @string is nul-terminated
1483 * @start_position: starting index of the string to match
1484 * @match_options: match time option flags
1485 * @max_tokens: the maximum number of tokens to split @string into. If this
1486 * is less than 1, the string is split completely
1487 * @error: return location for a #GError
1489 * Breaks the string on the pattern, and returns an array of the tokens.
1490 * If the pattern contains capturing parentheses, then the text for each
1491 * of the substrings will also be returned. If the pattern does not match
1492 * anywhere in the string, then the whole string is returned as the first
1495 * As a special case, the result of splitting the empty string "" is an
1496 * empty vector, not a vector containing a single string. The reason for
1497 * this special case is that being able to represent a empty vector is
1498 * typically more useful than consistent handling of empty elements. If
1499 * you do need to represent empty elements, you'll need to check for the
1500 * empty string before calling this function.
1502 * A pattern that can match empty strings splits @string into separate
1503 * characters wherever it matches the empty string between characters.
1504 * For example splitting "ab c" using as a separator "\s*", you will get
1507 * Setting @start_position differs from just passing over a shortened string
1508 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1509 * with any kind of lookbehind assertion, such as "\b".
1511 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1516 g_regex_split_full (const GRegex *regex,
1517 const gchar *string,
1519 gint start_position,
1520 GRegexMatchFlags match_options,
1524 GError *tmp_error = NULL;
1525 GMatchInfo *match_info;
1530 /* position of the last separator. */
1531 gint last_separator_end;
1532 /* was the last match 0 bytes long? */
1533 gboolean last_match_is_empty;
1534 /* the returned array of char **s */
1535 gchar **string_list;
1537 g_return_val_if_fail (regex != NULL, NULL);
1538 g_return_val_if_fail (string != NULL, NULL);
1539 g_return_val_if_fail (start_position >= 0, NULL);
1540 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1541 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1543 if (max_tokens <= 0)
1544 max_tokens = G_MAXINT;
1547 string_len = strlen (string);
1549 /* zero-length string */
1550 if (string_len - start_position == 0)
1551 return g_new0 (gchar *, 1);
1553 if (max_tokens == 1)
1555 string_list = g_new0 (gchar *, 2);
1556 string_list[0] = g_strndup (&string[start_position],
1557 string_len - start_position);
1563 last_separator_end = start_position;
1564 last_match_is_empty = FALSE;
1566 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1567 match_options, &match_info, &tmp_error);
1568 while (tmp_error == NULL)
1572 last_match_is_empty =
1573 (match_info->offsets[0] == match_info->offsets[1]);
1575 /* we need to skip empty separators at the same position of the end
1576 * of another separator. e.g. the string is "a b" and the separator
1577 * is " *", so from 1 to 2 we have a match and at position 2 we have
1578 * an empty match. */
1579 if (last_separator_end != match_info->offsets[1])
1584 token = g_strndup (string + last_separator_end,
1585 match_info->offsets[0] - last_separator_end);
1586 list = g_list_prepend (list, token);
1589 /* if there were substrings, these need to be added to
1591 match_count = g_match_info_get_match_count (match_info);
1592 if (match_count > 1)
1594 for (i = 1; i < match_count; i++)
1595 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1601 /* if there was no match, copy to end of string. */
1602 if (!last_match_is_empty)
1604 gchar *token = g_strndup (string + last_separator_end,
1605 match_info->string_len - last_separator_end);
1606 list = g_list_prepend (list, token);
1608 /* no more tokens, end the loop. */
1612 /* -1 to leave room for the last part. */
1613 if (token_count >= max_tokens - 1)
1615 /* we have reached the maximum number of tokens, so we copy
1616 * the remaining part of the string. */
1617 if (last_match_is_empty)
1619 /* the last match was empty, so we have moved one char
1620 * after the real position to avoid empty matches at the
1622 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1624 /* the if is needed in the case we have terminated the available
1625 * tokens, but we are at the end of the string, so there are no
1626 * characters left to copy. */
1627 if (string_len > match_info->pos)
1629 gchar *token = g_strndup (string + match_info->pos,
1630 string_len - match_info->pos);
1631 list = g_list_prepend (list, token);
1637 last_separator_end = match_info->pos;
1638 if (last_match_is_empty)
1639 /* if the last match was empty, g_match_info_next() has moved
1640 * forward to avoid infinite loops, but we still need to copy that
1642 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1644 match_ok = g_match_info_next (match_info, &tmp_error);
1646 g_match_info_free (match_info);
1647 if (tmp_error != NULL)
1649 g_propagate_error (error, tmp_error);
1650 g_list_foreach (list, (GFunc)g_free, NULL);
1652 match_info->pos = -1;
1656 string_list = g_new (gchar *, g_list_length (list) + 1);
1658 for (last = g_list_last (list); last; last = g_list_previous (last))
1659 string_list[i++] = last->data;
1669 REPL_TYPE_CHARACTER,
1670 REPL_TYPE_SYMBOLIC_REFERENCE,
1671 REPL_TYPE_NUMERIC_REFERENCE,
1672 REPL_TYPE_CHANGE_CASE
1677 CHANGE_CASE_NONE = 1 << 0,
1678 CHANGE_CASE_UPPER = 1 << 1,
1679 CHANGE_CASE_LOWER = 1 << 2,
1680 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1681 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1682 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1683 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1684 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1687 struct _InterpolationData
1693 ChangeCase change_case;
1697 free_interpolation_data (InterpolationData *data)
1699 g_free (data->text);
1703 static const gchar *
1704 expand_escape (const gchar *replacement,
1706 InterpolationData *data,
1711 const gchar *error_detail;
1713 GError *tmp_error = NULL;
1721 data->type = REPL_TYPE_CHARACTER;
1726 data->type = REPL_TYPE_CHARACTER;
1731 data->type = REPL_TYPE_CHARACTER;
1736 data->type = REPL_TYPE_CHARACTER;
1741 data->type = REPL_TYPE_CHARACTER;
1746 data->type = REPL_TYPE_CHARACTER;
1751 data->type = REPL_TYPE_CHARACTER;
1756 data->type = REPL_TYPE_CHARACTER;
1766 h = g_ascii_xdigit_value (*p);
1769 error_detail = _("hexadecimal digit or '}' expected");
1780 for (i = 0; i < 2; i++)
1782 h = g_ascii_xdigit_value (*p);
1785 error_detail = _("hexadecimal digit expected");
1792 data->type = REPL_TYPE_STRING;
1793 data->text = g_new0 (gchar, 8);
1794 g_unichar_to_utf8 (x, data->text);
1798 data->type = REPL_TYPE_CHANGE_CASE;
1799 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1803 data->type = REPL_TYPE_CHANGE_CASE;
1804 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1808 data->type = REPL_TYPE_CHANGE_CASE;
1809 data->change_case = CHANGE_CASE_LOWER;
1813 data->type = REPL_TYPE_CHANGE_CASE;
1814 data->change_case = CHANGE_CASE_UPPER;
1818 data->type = REPL_TYPE_CHANGE_CASE;
1819 data->change_case = CHANGE_CASE_NONE;
1825 error_detail = _("missing '<' in symbolic reference");
1834 error_detail = _("unfinished symbolic reference");
1841 error_detail = _("zero-length symbolic reference");
1844 if (g_ascii_isdigit (*q))
1849 h = g_ascii_digit_value (*q);
1852 error_detail = _("digit expected");
1861 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1868 if (!g_ascii_isalnum (*r))
1870 error_detail = _("illegal symbolic reference");
1877 data->text = g_strndup (q, p - q);
1878 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1883 /* if \0 is followed by a number is an octal number representing a
1884 * character, else it is a numeric reference. */
1885 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1888 p = g_utf8_next_char (p);
1901 for (i = 0; i < 3; i++)
1903 h = g_ascii_digit_value (*p);
1913 if (i == 2 && base == 10)
1919 if (base == 8 || i == 3)
1921 data->type = REPL_TYPE_STRING;
1922 data->text = g_new0 (gchar, 8);
1923 g_unichar_to_utf8 (x, data->text);
1927 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1932 error_detail = _("stray final '\\'");
1936 error_detail = _("unknown escape sequence");
1943 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1944 tmp_error = g_error_new (G_REGEX_ERROR,
1945 G_REGEX_ERROR_REPLACE,
1946 _("Error while parsing replacement "
1947 "text \"%s\" at char %lu: %s"),
1949 (gulong)(p - replacement),
1951 g_propagate_error (error, tmp_error);
1957 split_replacement (const gchar *replacement,
1961 InterpolationData *data;
1962 const gchar *p, *start;
1964 start = p = replacement;
1969 data = g_new0 (InterpolationData, 1);
1970 start = p = expand_escape (replacement, p, data, error);
1973 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1975 free_interpolation_data (data);
1979 list = g_list_prepend (list, data);
1984 if (*p == '\\' || *p == '\0')
1988 data = g_new0 (InterpolationData, 1);
1989 data->text = g_strndup (start, p - start);
1990 data->type = REPL_TYPE_STRING;
1991 list = g_list_prepend (list, data);
1997 return g_list_reverse (list);
2000 /* Change the case of c based on change_case. */
2001 #define CHANGE_CASE(c, change_case) \
2002 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2003 g_unichar_tolower (c) : \
2004 g_unichar_toupper (c))
2007 string_append (GString *string,
2009 ChangeCase *change_case)
2013 if (text[0] == '\0')
2016 if (*change_case == CHANGE_CASE_NONE)
2018 g_string_append (string, text);
2020 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2022 c = g_utf8_get_char (text);
2023 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2024 g_string_append (string, g_utf8_next_char (text));
2025 *change_case = CHANGE_CASE_NONE;
2029 while (*text != '\0')
2031 c = g_utf8_get_char (text);
2032 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2033 text = g_utf8_next_char (text);
2039 interpolate_replacement (const GMatchInfo *match_info,
2044 InterpolationData *idata;
2046 ChangeCase change_case = CHANGE_CASE_NONE;
2048 for (list = data; list; list = list->next)
2051 switch (idata->type)
2053 case REPL_TYPE_STRING:
2054 string_append (result, idata->text, &change_case);
2056 case REPL_TYPE_CHARACTER:
2057 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2058 if (change_case & CHANGE_CASE_SINGLE_MASK)
2059 change_case = CHANGE_CASE_NONE;
2061 case REPL_TYPE_NUMERIC_REFERENCE:
2062 match = g_match_info_fetch (match_info, idata->num);
2065 string_append (result, match, &change_case);
2069 case REPL_TYPE_SYMBOLIC_REFERENCE:
2070 match = g_match_info_fetch_named (match_info, idata->text);
2073 string_append (result, match, &change_case);
2077 case REPL_TYPE_CHANGE_CASE:
2078 change_case = idata->change_case;
2086 /* whether actual match_info is needed for replacement, i.e.
2087 * whether there are references
2090 interpolation_list_needs_match (GList *list)
2092 while (list != NULL)
2094 InterpolationData *data = list->data;
2096 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2097 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2110 * @regex: a #GRegex structure
2111 * @string: the string to perform matches against
2112 * @string_len: the length of @string, or -1 if @string is nul-terminated
2113 * @start_position: starting index of the string to match
2114 * @replacement: text to replace each match with
2115 * @match_options: options for the match
2116 * @error: location to store the error occuring, or %NULL to ignore errors
2118 * Replaces all occurances of the pattern in @regex with the
2119 * replacement text. Backreferences of the form '\number' or '\g<number>'
2120 * in the replacement text are interpolated by the number-th captured
2121 * subexpression of the match, '\g<name>' refers to the captured subexpression
2122 * with the given name. '\0' refers to the complete match, but '\0' followed
2123 * by a number is the octal representation of a character. To include a
2124 * literal '\' in the replacement, write '\\'.
2125 * There are also escapes that changes the case of the following text:
2128 * <varlistentry><term>\l</term>
2130 * <para>Convert to lower case the next character</para>
2133 * <varlistentry><term>\u</term>
2135 * <para>Convert to upper case the next character</para>
2138 * <varlistentry><term>\L</term>
2140 * <para>Convert to lower case till \E</para>
2143 * <varlistentry><term>\U</term>
2145 * <para>Convert to upper case till \E</para>
2148 * <varlistentry><term>\E</term>
2150 * <para>End case modification</para>
2155 * If you do not need to use backreferences use g_regex_replace_literal().
2157 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2158 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2159 * you can use g_regex_replace_literal().
2161 * Setting @start_position differs from just passing over a shortened string
2162 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2163 * with any kind of lookbehind assertion, such as "\b".
2165 * Returns: a newly allocated string containing the replacements
2170 g_regex_replace (const GRegex *regex,
2171 const gchar *string,
2173 gint start_position,
2174 const gchar *replacement,
2175 GRegexMatchFlags match_options,
2180 GError *tmp_error = NULL;
2182 g_return_val_if_fail (regex != NULL, NULL);
2183 g_return_val_if_fail (string != NULL, NULL);
2184 g_return_val_if_fail (start_position >= 0, NULL);
2185 g_return_val_if_fail (replacement != NULL, NULL);
2186 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2187 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2189 list = split_replacement (replacement, &tmp_error);
2190 if (tmp_error != NULL)
2192 g_propagate_error (error, tmp_error);
2196 result = g_regex_replace_eval (regex,
2197 string, string_len, start_position,
2199 interpolate_replacement,
2202 if (tmp_error != NULL)
2203 g_propagate_error (error, tmp_error);
2205 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2212 literal_replacement (const GMatchInfo *match_info,
2216 g_string_append (result, data);
2221 * g_regex_replace_literal:
2222 * @regex: a #GRegex structure
2223 * @string: the string to perform matches against
2224 * @string_len: the length of @string, or -1 if @string is nul-terminated
2225 * @start_position: starting index of the string to match
2226 * @replacement: text to replace each match with
2227 * @match_options: options for the match
2228 * @error: location to store the error occuring, or %NULL to ignore errors
2230 * Replaces all occurances of the pattern in @regex with the
2231 * replacement text. @replacement is replaced literally, to
2232 * include backreferences use g_regex_replace().
2234 * Setting @start_position differs from just passing over a shortened string
2235 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2236 * with any kind of lookbehind assertion, such as "\b".
2238 * Returns: a newly allocated string containing the replacements
2243 g_regex_replace_literal (const GRegex *regex,
2244 const gchar *string,
2246 gint start_position,
2247 const gchar *replacement,
2248 GRegexMatchFlags match_options,
2251 g_return_val_if_fail (replacement != NULL, NULL);
2252 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2254 return g_regex_replace_eval (regex,
2255 string, string_len, start_position,
2257 literal_replacement,
2258 (gpointer)replacement,
2263 * g_regex_replace_eval:
2264 * @regex: a #GRegex structure from g_regex_new()
2265 * @string: string to perform matches against
2266 * @string_len: the length of @string, or -1 if @string is nul-terminated
2267 * @start_position: starting index of the string to match
2268 * @match_options: options for the match
2269 * @eval: a function to call for each match
2270 * @user_data: user data to pass to the function
2271 * @error: location to store the error occuring, or %NULL to ignore errors
2273 * Replaces occurances of the pattern in regex with the output of @eval
2274 * for that occurance.
2276 * Setting @start_position differs from just passing over a shortened string
2277 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2278 * with any kind of lookbehind assertion, such as "\b".
2280 * Returns: a newly allocated string containing the replacements
2285 g_regex_replace_eval (const GRegex *regex,
2286 const gchar *string,
2288 gint start_position,
2289 GRegexMatchFlags match_options,
2290 GRegexEvalCallback eval,
2294 GMatchInfo *match_info;
2297 gboolean done = FALSE;
2298 GError *tmp_error = NULL;
2300 g_return_val_if_fail (regex != NULL, NULL);
2301 g_return_val_if_fail (string != NULL, NULL);
2302 g_return_val_if_fail (start_position >= 0, NULL);
2303 g_return_val_if_fail (eval != NULL, NULL);
2304 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2307 string_len = strlen (string);
2309 result = g_string_sized_new (string_len);
2311 /* run down the string making matches. */
2312 g_regex_match_full (regex, string, string_len, start_position,
2313 match_options, &match_info, &tmp_error);
2314 while (!done && g_match_info_matches (match_info))
2316 g_string_append_len (result,
2318 match_info->offsets[0] - str_pos);
2319 done = (*eval) (match_info, result, user_data);
2320 str_pos = match_info->offsets[1];
2321 g_match_info_next (match_info, &tmp_error);
2323 g_match_info_free (match_info);
2324 if (tmp_error != NULL)
2326 g_propagate_error (error, tmp_error);
2327 g_string_free (result, TRUE);
2331 g_string_append_len (result, string + str_pos, string_len - str_pos);
2332 return g_string_free (result, FALSE);
2336 * g_regex_check_replacement:
2337 * @replacement: the replacement string
2338 * @has_references: location to store information about
2339 * references in @replacement or %NULL
2340 * @error: location to store error
2342 * Checks whether @replacement is a valid replacement string (see g_regex_replace()),
2343 * i.e. that all escape sequences in it are valid.
2345 * If @has_references is not %NULL then @replacement is checked for
2346 * pattern references. For instance, replacement text 'foo\n'
2347 * does not contain references and may be evaluated without information
2348 * about actual match, but '\0\1' (whole match followed by first subpattern)
2349 * requires valid #GMatchInfo object.
2351 * Returns: whether @replacement is a valid replacement string
2356 g_regex_check_replacement (const gchar *replacement,
2357 gboolean *has_references,
2363 list = split_replacement (replacement, &tmp);
2367 g_propagate_error (error, tmp);
2372 *has_references = interpolation_list_needs_match (list);
2374 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2381 * g_regex_escape_string:
2382 * @string: the string to escape
2383 * @length: the length of @string, or -1 if @string is nul-terminated
2385 * Escapes the special characters used for regular expressions in @string,
2386 * for instance "a.b*c" becomes "a\.b\*c". This function is useful to
2387 * dynamically generate regular expressions.
2389 * @string can contain nul characters that are replaced with "\0", in this
2390 * case remember to specify the correct length of @string in @length.
2392 * Returns: a newly-allocated escaped string
2397 g_regex_escape_string (const gchar *string,
2401 const char *p, *piece_start, *end;
2403 g_return_val_if_fail (string != NULL, NULL);
2406 length = strlen (string);
2408 end = string + length;
2409 p = piece_start = string;
2410 escaped = g_string_sized_new (length + 1);
2431 if (p != piece_start)
2432 /* copy the previous piece. */
2433 g_string_append_len (escaped, piece_start, p - piece_start);
2434 g_string_append_c (escaped, '\\');
2436 g_string_append_c (escaped, '0');
2438 g_string_append_c (escaped, *p);
2442 p = g_utf8_next_char (p);
2447 if (piece_start < end)
2448 g_string_append_len (escaped, piece_start, end - piece_start);
2450 return g_string_free (escaped, FALSE);
2453 #define __G_REGEX_C__
2454 #include "galiasdef.c"