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,
627 * FIXME: (?J) may be used inside the pattern as the equivalent of
628 * DUPNAMES compile option. In this case we can't know about it,
629 * and pcre doesn't tell us about it either, it uses private flag
630 * PCRE_JCHANGED for this. So we have to always search string
631 * table, unlike pcre which uses pcre_get_stringnumber() shortcut
632 * when possible. It shouldn't be actually bad since
633 * pcre_get_stringtable_entries() uses binary search; still would
634 * be better to fix it, to be not worse than pcre.
637 if ((match_info->regex->compile_opts & G_REGEX_DUPNAMES) == 0)
638 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
641 /* This code is copied from pcre_get.c: get_first_set() */
642 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
650 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
652 gint n = (entry[0] << 8) + entry[1];
653 if (match_info->offsets[n*2] >= 0)
657 return (first[0] << 8) + first[1];
661 * g_match_info_fetch_named:
662 * @match_info: #GMatchInfo structure
663 * @name: name of the subexpression
665 * Retrieves the text matching the capturing parentheses named @name.
667 * If @name is a valid sub pattern name but it didn't match anything
668 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
669 * then an empty string is returned.
671 * The string is fetched from the string passed to the match function,
672 * so you cannot call this function after freeing the string.
674 * Returns: The matched substring, or %NULL if an error occurred.
675 * You have to free the string yourself
680 g_match_info_fetch_named (const GMatchInfo *match_info,
683 /* we cannot use pcre_get_named_substring() because it allocates the
684 * string using pcre_malloc(). */
687 g_return_val_if_fail (match_info != NULL, NULL);
688 g_return_val_if_fail (name != NULL, NULL);
690 num = get_matched_substring_number (match_info, name);
694 return g_match_info_fetch (match_info, num);
698 * g_match_info_fetch_named_pos:
699 * @match_info: #GMatchInfo structure
700 * @name: name of the subexpression
701 * @start_pos: pointer to location where to store the start position
702 * @end_pos: pointer to location where to store the end position
704 * Retrieves the position of the capturing parentheses named @name.
706 * If @name is a valid sub pattern name but it didn't match anything
707 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
708 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
710 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
711 * the position cannot be fetched, @start_pos and @end_pos are left
717 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
724 g_return_val_if_fail (match_info != NULL, FALSE);
725 g_return_val_if_fail (name != NULL, FALSE);
727 num = get_matched_substring_number (match_info, name);
731 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
735 * g_match_info_fetch_all:
736 * @match_info: a #GMatchInfo structure
738 * Bundles up pointers to each of the matching substrings from a match
739 * and stores them in an array of gchar pointers. The first element in
740 * the returned array is the match number 0, i.e. the entire matched
743 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
744 * "b" against "(a)?b") then an empty string is inserted.
746 * If the last match was obtained using the DFA algorithm, that is using
747 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
748 * strings are not that matched by sets of parentheses but that of the
749 * matched substring. Substrings are matched in reverse order of length,
750 * so the first one is the longest match.
752 * The strings are fetched from the string passed to the match function,
753 * so you cannot call this function after freeing the string.
755 * Returns: a %NULL-terminated array of gchar * pointers. It must be
756 * freed using g_strfreev(). If the previous match failed %NULL is
762 g_match_info_fetch_all (const GMatchInfo *match_info)
764 /* we cannot use pcre_get_substring_list() because the returned value
765 * isn't suitable for g_strfreev(). */
769 g_return_val_if_fail (match_info != NULL, FALSE);
771 if (match_info->matches < 0)
774 result = g_new (gchar *, match_info->matches + 1);
775 for (i = 0; i < match_info->matches; i++)
776 result[i] = g_match_info_fetch (match_info, i);
786 g_regex_error_quark (void)
788 static GQuark error_quark = 0;
790 if (error_quark == 0)
791 error_quark = g_quark_from_static_string ("g-regex-error-quark");
800 * Increases reference count of @regex by 1.
807 g_regex_ref (GRegex *regex)
809 g_return_val_if_fail (regex != NULL, NULL);
810 g_atomic_int_inc ((gint*) ®ex->ref_count);
818 * Decreases reference count of @regex by 1. When reference count drops
819 * to zero, it frees all the memory associated with the regex structure.
824 g_regex_unref (GRegex *regex)
826 g_return_if_fail (regex != NULL);
828 if (g_atomic_int_exchange_and_add ((gint *) ®ex->ref_count, -1) - 1 == 0)
830 g_free (regex->pattern);
831 if (regex->pcre_re != NULL)
832 pcre_free (regex->pcre_re);
833 if (regex->extra != NULL)
834 pcre_free (regex->extra);
841 * @pattern: the regular expression
842 * @compile_options: compile options for the regular expression
843 * @match_options: match options for the regular expression
844 * @error: return location for a #GError
846 * Compiles the regular expression to an internal form, and does
847 * the initial setup of the #GRegex structure.
849 * Returns: a #GRegex structure. Call g_regex_unref() when you
855 g_regex_new (const gchar *pattern,
856 GRegexCompileFlags compile_options,
857 GRegexMatchFlags match_options,
864 gboolean optimize = FALSE;
865 static gboolean initialized = FALSE;
867 g_return_val_if_fail (pattern != NULL, NULL);
868 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
869 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
870 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
877 pcre_config (PCRE_CONFIG_UTF8, &support);
880 msg = N_("PCRE library is compiled without UTF8 support");
882 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
886 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
889 msg = N_("PCRE library is compiled without UTF8 properties support");
891 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
898 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
899 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
900 if (compile_options & G_REGEX_OPTIMIZE)
903 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
904 * instead uses UTF-8 only if required with PCRE_UTF8. */
905 if (compile_options & G_REGEX_RAW)
908 compile_options &= ~G_REGEX_RAW;
913 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
914 match_options |= PCRE_NO_UTF8_CHECK;
917 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
918 * not for the system one. */
919 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
920 !(compile_options & G_REGEX_NEWLINE_LF))
922 compile_options |= PCRE_NEWLINE_ANY;
925 g_print ("compile opts: %x\n", compile_options);
926 if (compile_options & PCRE_UTF8)
927 g_print ("\tPCRE_UTF8\n");
928 if (compile_options & PCRE_NO_UTF8_CHECK)
929 g_print ("\tPCRE_NO_UTF8_CHECK\n");
930 if (compile_options & PCRE_NEWLINE_ANY)
931 g_print ("\tPCRE_NEWLINE_ANY\n");
932 /* compile the pattern */
933 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
935 /* if the compilation failed, set the error member and return
939 GError *tmp_error = g_error_new (G_REGEX_ERROR,
940 G_REGEX_ERROR_COMPILE,
941 _("Error while compiling regular "
942 "expression %s at char %d: %s"),
943 pattern, erroffset, errmsg);
944 g_propagate_error (error, tmp_error);
949 regex = g_new0 (GRegex, 1);
950 regex->ref_count = 1;
951 regex->pattern = g_strdup (pattern);
953 regex->compile_opts = compile_options;
954 regex->match_opts = match_options;
958 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
961 GError *tmp_error = g_error_new (G_REGEX_ERROR,
962 G_REGEX_ERROR_OPTIMIZE,
963 _("Error while optimizing "
964 "regular expression %s: %s"),
967 g_propagate_error (error, tmp_error);
976 * g_regex_get_pattern:
977 * @regex: a #GRegex structure
979 * Gets the pattern string associated with @regex, i.e. a copy of
980 * the string passed to g_regex_new().
982 * Returns: the pattern of @regex
987 g_regex_get_pattern (const GRegex *regex)
989 g_return_val_if_fail (regex != NULL, NULL);
991 return regex->pattern;
995 * g_regex_get_max_backref:
998 * Returns the number of the highest back reference
999 * in the pattern, or 0 if the pattern does not contain
1002 * Returns: the number of the highest back reference
1007 g_regex_get_max_backref (const GRegex *regex)
1011 pcre_fullinfo (regex->pcre_re, regex->extra,
1012 PCRE_INFO_BACKREFMAX, &value);
1018 * g_regex_get_capture_count:
1021 * Returns the number of capturing subpatterns in the pattern.
1023 * Returns: the number of capturing subpatterns
1028 g_regex_get_capture_count (const GRegex *regex)
1032 pcre_fullinfo (regex->pcre_re, regex->extra,
1033 PCRE_INFO_CAPTURECOUNT, &value);
1039 * g_regex_match_simple:
1040 * @pattern: the regular expression
1041 * @string: the string to scan for matches
1042 * @compile_options: compile options for the regular expression
1043 * @match_options: match options
1045 * Scans for a match in @string for @pattern.
1047 * This function is equivalent to g_regex_match() but it does not
1048 * require to compile the pattern with g_regex_new(), avoiding some
1049 * lines of code when you need just to do a match without extracting
1050 * substrings, capture counts, and so on.
1052 * If this function is to be called on the same @pattern more than
1053 * once, it's more efficient to compile the pattern once with
1054 * g_regex_new() and then use g_regex_match().
1056 * Returns: %TRUE is the string matched, %FALSE otherwise
1061 g_regex_match_simple (const gchar *pattern,
1062 const gchar *string,
1063 GRegexCompileFlags compile_options,
1064 GRegexMatchFlags match_options)
1069 regex = g_regex_new (pattern, compile_options, 0, NULL);
1072 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1073 g_regex_unref (regex);
1079 * @regex: a #GRegex structure from g_regex_new()
1080 * @string: the string to scan for matches
1081 * @match_options: match options
1082 * @match_info: pointer to location where to store the #GMatchInfo,
1083 * or %NULL if you do not need it
1085 * Scans for a match in string for the pattern in @regex.
1086 * The @match_options are combined with the match options specified
1087 * when the @regex structure was created, letting you have more
1088 * flexibility in reusing #GRegex structures.
1090 * A #GMatchInfo structure, used to get information on the match,
1091 * is stored in @match_info if not %NULL. Note that if @match_info
1092 * is not %NULL then it is created even if the function returns %FALSE,
1093 * i.e. you must free it regardless if regular expression actually matched.
1095 * To retrieve all the non-overlapping matches of the pattern in
1096 * string you can use g_match_info_next().
1098 * <informalexample><programlisting>
1100 * print_uppercase_words (const gchar *string)
1102 * /* Print all uppercase-only words. */
1104 * GMatchInfo *match_info;
1106 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1107 * g_regex_match (regex, string, 0, &match_info);
1108 * while (g_match_info_matches (match_info))
1110 * gchar *word = g_match_info_fetch (match_info, 0);
1111 * g_print ("Found: %s\n", word);
1113 * g_match_info_next (match_info, NULL);
1115 * g_match_info_free (match_info);
1116 * g_regex_unref (regex);
1118 * </programlisting></informalexample>
1120 * Returns: %TRUE is the string matched, %FALSE otherwise
1125 g_regex_match (const GRegex *regex,
1126 const gchar *string,
1127 GRegexMatchFlags match_options,
1128 GMatchInfo **match_info)
1130 return g_regex_match_full (regex, string, -1, 0, match_options,
1135 * g_regex_match_full:
1136 * @regex: a #GRegex structure from g_regex_new()
1137 * @string: the string to scan for matches
1138 * @string_len: the length of @string, or -1 if @string is nul-terminated
1139 * @start_position: starting index of the string to match
1140 * @match_options: match options
1141 * @match_info: pointer to location where to store the #GMatchInfo,
1142 * or %NULL if you do not need it
1143 * @error: location to store the error occuring, or %NULL to ignore errors
1145 * Scans for a match in string for the pattern in @regex.
1146 * The @match_options are combined with the match options specified
1147 * when the @regex structure was created, letting you have more
1148 * flexibility in reusing #GRegex structures.
1150 * Setting @start_position differs from just passing over a shortened
1151 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1152 * that begins with any kind of lookbehind assertion, such as "\b".
1154 * A #GMatchInfo structure, used to get information on the match, is
1155 * stored in @match_info if not %NULL. Note that if @match_info is
1156 * not %NULL then it is created even if the function returns %FALSE,
1157 * i.e. you must free it regardless if regular expression actually
1160 * @string is not copied and is used in #GMatchInfo internally. If
1161 * you use any #GMatchInfo method (except g_match_info_free()) after
1162 * freeing or modifying @string then the behaviour is undefined.
1164 * To retrieve all the non-overlapping matches of the pattern in
1165 * string you can use g_match_info_next().
1167 * <informalexample><programlisting>
1169 * print_uppercase_words (const gchar *string)
1171 * /* Print all uppercase-only words. */
1173 * GMatchInfo *match_info;
1174 * GError *error = NULL;
1176 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1177 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1178 * while (g_match_info_matches (match_info))
1180 * gchar *word = g_match_info_fetch (match_info, 0);
1181 * g_print ("Found: %s\n", word);
1183 * g_match_info_next (match_info, &error);
1185 * g_match_info_free (match_info);
1186 * g_regex_unref (regex);
1187 * if (error != NULL)
1189 * g_printerr ("Error while matching: %s\n", error->message);
1190 * g_error_free (error);
1193 * </programlisting></informalexample>
1195 * Returns: %TRUE is the string matched, %FALSE otherwise
1200 g_regex_match_full (const GRegex *regex,
1201 const gchar *string,
1203 gint start_position,
1204 GRegexMatchFlags match_options,
1205 GMatchInfo **match_info,
1211 g_return_val_if_fail (regex != NULL, FALSE);
1212 g_return_val_if_fail (string != NULL, FALSE);
1213 g_return_val_if_fail (start_position >= 0, FALSE);
1214 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1215 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1217 info = match_info_new (regex, string, string_len, start_position,
1218 match_options, FALSE);
1219 match_ok = g_match_info_next (info, error);
1220 if (match_info != NULL)
1223 g_match_info_free (info);
1229 * g_regex_match_all:
1230 * @regex: a #GRegex structure from g_regex_new()
1231 * @string: the string to scan for matches
1232 * @match_options: match options
1233 * @match_info: pointer to location where to store the #GMatchInfo,
1234 * or %NULL if you do not need it
1236 * Using the standard algorithm for regular expression matching only
1237 * the longest match in the string is retrieved. This function uses
1238 * a different algorithm so it can retrieve all the possible matches.
1239 * For more documentation see g_regex_match_all_full().
1241 * A #GMatchInfo structure, used to get information on the match, is
1242 * stored in @match_info if not %NULL. Note that if @match_info is
1243 * not %NULL then it is created even if the function returns %FALSE,
1244 * i.e. you must free it regardless if regular expression actually
1247 * Returns: %TRUE is the string matched, %FALSE otherwise
1252 g_regex_match_all (const GRegex *regex,
1253 const gchar *string,
1254 GRegexMatchFlags match_options,
1255 GMatchInfo **match_info)
1257 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1262 * g_regex_match_all_full:
1263 * @regex: a #GRegex structure from g_regex_new()
1264 * @string: the string to scan for matches
1265 * @string_len: the length of @string, or -1 if @string is nul-terminated
1266 * @start_position: starting index of the string to match
1267 * @match_options: match options
1268 * @match_info: pointer to location where to store the #GMatchInfo,
1269 * or %NULL if you do not need it
1270 * @error: location to store the error occuring, or %NULL to ignore errors
1272 * Using the standard algorithm for regular expression matching only
1273 * the longest match in the string is retrieved, it is not possibile
1274 * to obtain all the available matches. For instance matching
1275 * "<a> <b> <c>" against the pattern "<.*>"
1276 * you get "<a> <b> <c>".
1278 * This function uses a different algorithm (called DFA, i.e. deterministic
1279 * finite automaton), so it can retrieve all the possible matches, all
1280 * starting at the same point in the string. For instance matching
1281 * "<a> <b> <c>" against the pattern "<.*>"
1282 * you would obtain three matches: "<a> <b> <c>",
1283 * "<a> <b>" and "<a>".
1285 * The number of matched strings is retrieved using
1286 * g_match_info_get_match_count(). To obtain the matched strings and
1287 * their position you can use, respectively, g_match_info_fetch() and
1288 * g_match_info_fetch_pos(). Note that the strings are returned in
1289 * reverse order of length; that is, the longest matching string is
1292 * Note that the DFA algorithm is slower than the standard one and it
1293 * is not able to capture substrings, so backreferences do not work.
1295 * Setting @start_position differs from just passing over a shortened
1296 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1297 * that begins with any kind of lookbehind assertion, such as "\b".
1299 * A #GMatchInfo structure, used to get information on the match, is
1300 * stored in @match_info if not %NULL. Note that if @match_info is
1301 * not %NULL then it is created even if the function returns %FALSE,
1302 * i.e. you must free it regardless if regular expression actually
1305 * Returns: %TRUE is the string matched, %FALSE otherwise
1310 g_regex_match_all_full (const GRegex *regex,
1311 const gchar *string,
1313 gint start_position,
1314 GRegexMatchFlags match_options,
1315 GMatchInfo **match_info,
1321 g_return_val_if_fail (regex != NULL, FALSE);
1322 g_return_val_if_fail (string != NULL, FALSE);
1323 g_return_val_if_fail (start_position >= 0, FALSE);
1324 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1327 info = match_info_new (regex, string, string_len, start_position,
1328 match_options, TRUE);
1334 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1335 info->string, info->string_len,
1337 regex->match_opts | match_options,
1338 info->offsets, info->n_offsets,
1339 info->workspace, info->n_workspace);
1340 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1342 /* info->workspace is too small. */
1343 info->n_workspace *= 2;
1344 info->workspace = g_realloc (info->workspace,
1345 info->n_workspace * sizeof (gint));
1348 else if (info->matches == 0)
1350 /* info->offsets is too small. */
1351 info->n_offsets *= 2;
1352 info->offsets = g_realloc (info->offsets,
1353 info->n_offsets * sizeof (gint));
1356 else if (IS_PCRE_ERROR (info->matches))
1358 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1359 _("Error while matching regular expression %s: %s"),
1360 regex->pattern, match_error (info->matches));
1364 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1367 if (match_info != NULL)
1370 g_match_info_free (info);
1372 return info->matches >= 0;
1376 * g_regex_get_string_number:
1377 * @regex: #GRegex structure
1378 * @name: name of the subexpression
1380 * Retrieves the number of the subexpression named @name.
1382 * Returns: The number of the subexpression or -1 if @name
1388 g_regex_get_string_number (const GRegex *regex,
1393 g_return_val_if_fail (regex != NULL, -1);
1394 g_return_val_if_fail (name != NULL, -1);
1396 num = pcre_get_stringnumber (regex->pcre_re, name);
1397 if (num == PCRE_ERROR_NOSUBSTRING)
1404 * g_regex_split_simple:
1405 * @pattern: the regular expression
1406 * @string: the string to scan for matches
1407 * @compile_options: compile options for the regular expression
1408 * @match_options: match options
1410 * Breaks the string on the pattern, and returns an array of
1411 * the tokens. If the pattern contains capturing parentheses,
1412 * then the text for each of the substrings will also be returned.
1413 * If the pattern does not match anywhere in the string, then the
1414 * whole string is returned as the first token.
1416 * This function is equivalent to g_regex_split() but it does
1417 * not require to compile the pattern with g_regex_new(), avoiding
1418 * some lines of code when you need just to do a split without
1419 * extracting substrings, capture counts, and so on.
1421 * If this function is to be called on the same @pattern more than
1422 * once, it's more efficient to compile the pattern once with
1423 * g_regex_new() and then use g_regex_split().
1425 * As a special case, the result of splitting the empty string ""
1426 * is an empty vector, not a vector containing a single string.
1427 * The reason for this special case is that being able to represent
1428 * a empty vector is typically more useful than consistent handling
1429 * of empty elements. If you do need to represent empty elements,
1430 * you'll need to check for the empty string before calling this
1433 * A pattern that can match empty strings splits @string into
1434 * separate characters wherever it matches the empty string between
1435 * characters. For example splitting "ab c" using as a separator
1436 * "\s*", you will get "a", "b" and "c".
1438 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1443 g_regex_split_simple (const gchar *pattern,
1444 const gchar *string,
1445 GRegexCompileFlags compile_options,
1446 GRegexMatchFlags match_options)
1451 regex = g_regex_new (pattern, compile_options, 0, NULL);
1454 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1455 g_regex_unref (regex);
1461 * @regex: a #GRegex structure
1462 * @string: the string to split with the pattern
1463 * @match_options: match time option flags
1465 * Breaks the string on the pattern, and returns an array of the tokens.
1466 * If the pattern contains capturing parentheses, then the text for each
1467 * of the substrings will also be returned. If the pattern does not match
1468 * anywhere in the string, then the whole string is returned as the first
1471 * As a special case, the result of splitting the empty string "" is an
1472 * empty vector, not a vector containing a single string. The reason for
1473 * this special case is that being able to represent a empty vector is
1474 * typically more useful than consistent handling of empty elements. If
1475 * you do need to represent empty elements, you'll need to check for the
1476 * empty string before calling this function.
1478 * A pattern that can match empty strings splits @string into separate
1479 * characters wherever it matches the empty string between characters.
1480 * For example splitting "ab c" using as a separator "\s*", you will get
1483 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1488 g_regex_split (const GRegex *regex,
1489 const gchar *string,
1490 GRegexMatchFlags match_options)
1492 return g_regex_split_full (regex, string, -1, 0,
1493 match_options, 0, NULL);
1497 * g_regex_split_full:
1498 * @regex: a #GRegex structure
1499 * @string: the string to split with the pattern
1500 * @string_len: the length of @string, or -1 if @string is nul-terminated
1501 * @start_position: starting index of the string to match
1502 * @match_options: match time option flags
1503 * @max_tokens: the maximum number of tokens to split @string into.
1504 * If this is less than 1, the string is split completely
1505 * @error: return location for a #GError
1507 * Breaks the string on the pattern, and returns an array of the tokens.
1508 * If the pattern contains capturing parentheses, then the text for each
1509 * of the substrings will also be returned. If the pattern does not match
1510 * anywhere in the string, then the whole string is returned as the first
1513 * As a special case, the result of splitting the empty string "" is an
1514 * empty vector, not a vector containing a single string. The reason for
1515 * this special case is that being able to represent a empty vector is
1516 * typically more useful than consistent handling of empty elements. If
1517 * you do need to represent empty elements, you'll need to check for the
1518 * empty string before calling this function.
1520 * A pattern that can match empty strings splits @string into separate
1521 * characters wherever it matches the empty string between characters.
1522 * For example splitting "ab c" using as a separator "\s*", you will get
1525 * Setting @start_position differs from just passing over a shortened
1526 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1527 * that begins with any kind of lookbehind assertion, such as "\b".
1529 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1534 g_regex_split_full (const GRegex *regex,
1535 const gchar *string,
1537 gint start_position,
1538 GRegexMatchFlags match_options,
1542 GError *tmp_error = NULL;
1543 GMatchInfo *match_info;
1548 /* position of the last separator. */
1549 gint last_separator_end;
1550 /* was the last match 0 bytes long? */
1551 gboolean last_match_is_empty;
1552 /* the returned array of char **s */
1553 gchar **string_list;
1555 g_return_val_if_fail (regex != NULL, NULL);
1556 g_return_val_if_fail (string != NULL, NULL);
1557 g_return_val_if_fail (start_position >= 0, NULL);
1558 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1559 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1561 if (max_tokens <= 0)
1562 max_tokens = G_MAXINT;
1565 string_len = strlen (string);
1567 /* zero-length string */
1568 if (string_len - start_position == 0)
1569 return g_new0 (gchar *, 1);
1571 if (max_tokens == 1)
1573 string_list = g_new0 (gchar *, 2);
1574 string_list[0] = g_strndup (&string[start_position],
1575 string_len - start_position);
1581 last_separator_end = start_position;
1582 last_match_is_empty = FALSE;
1584 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1585 match_options, &match_info, &tmp_error);
1586 while (tmp_error == NULL)
1590 last_match_is_empty =
1591 (match_info->offsets[0] == match_info->offsets[1]);
1593 /* we need to skip empty separators at the same position of the end
1594 * of another separator. e.g. the string is "a b" and the separator
1595 * is " *", so from 1 to 2 we have a match and at position 2 we have
1596 * an empty match. */
1597 if (last_separator_end != match_info->offsets[1])
1602 token = g_strndup (string + last_separator_end,
1603 match_info->offsets[0] - last_separator_end);
1604 list = g_list_prepend (list, token);
1607 /* if there were substrings, these need to be added to
1609 match_count = g_match_info_get_match_count (match_info);
1610 if (match_count > 1)
1612 for (i = 1; i < match_count; i++)
1613 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1619 /* if there was no match, copy to end of string. */
1620 if (!last_match_is_empty)
1622 gchar *token = g_strndup (string + last_separator_end,
1623 match_info->string_len - last_separator_end);
1624 list = g_list_prepend (list, token);
1626 /* no more tokens, end the loop. */
1630 /* -1 to leave room for the last part. */
1631 if (token_count >= max_tokens - 1)
1633 /* we have reached the maximum number of tokens, so we copy
1634 * the remaining part of the string. */
1635 if (last_match_is_empty)
1637 /* the last match was empty, so we have moved one char
1638 * after the real position to avoid empty matches at the
1640 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1642 /* the if is needed in the case we have terminated the available
1643 * tokens, but we are at the end of the string, so there are no
1644 * characters left to copy. */
1645 if (string_len > match_info->pos)
1647 gchar *token = g_strndup (string + match_info->pos,
1648 string_len - match_info->pos);
1649 list = g_list_prepend (list, token);
1655 last_separator_end = match_info->pos;
1656 if (last_match_is_empty)
1657 /* if the last match was empty, g_match_info_next() has moved
1658 * forward to avoid infinite loops, but we still need to copy that
1660 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1662 match_ok = g_match_info_next (match_info, &tmp_error);
1664 g_match_info_free (match_info);
1665 if (tmp_error != NULL)
1667 g_propagate_error (error, tmp_error);
1668 g_list_foreach (list, (GFunc)g_free, NULL);
1670 match_info->pos = -1;
1674 string_list = g_new (gchar *, g_list_length (list) + 1);
1676 for (last = g_list_last (list); last; last = g_list_previous (last))
1677 string_list[i++] = last->data;
1687 REPL_TYPE_CHARACTER,
1688 REPL_TYPE_SYMBOLIC_REFERENCE,
1689 REPL_TYPE_NUMERIC_REFERENCE,
1690 REPL_TYPE_CHANGE_CASE
1695 CHANGE_CASE_NONE = 1 << 0,
1696 CHANGE_CASE_UPPER = 1 << 1,
1697 CHANGE_CASE_LOWER = 1 << 2,
1698 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1699 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1700 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1701 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1702 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1705 struct _InterpolationData
1711 ChangeCase change_case;
1715 free_interpolation_data (InterpolationData *data)
1717 g_free (data->text);
1721 static const gchar *
1722 expand_escape (const gchar *replacement,
1724 InterpolationData *data,
1729 const gchar *error_detail;
1731 GError *tmp_error = NULL;
1739 data->type = REPL_TYPE_CHARACTER;
1744 data->type = REPL_TYPE_CHARACTER;
1749 data->type = REPL_TYPE_CHARACTER;
1754 data->type = REPL_TYPE_CHARACTER;
1759 data->type = REPL_TYPE_CHARACTER;
1764 data->type = REPL_TYPE_CHARACTER;
1769 data->type = REPL_TYPE_CHARACTER;
1774 data->type = REPL_TYPE_CHARACTER;
1784 h = g_ascii_xdigit_value (*p);
1787 error_detail = _("hexadecimal digit or '}' expected");
1798 for (i = 0; i < 2; i++)
1800 h = g_ascii_xdigit_value (*p);
1803 error_detail = _("hexadecimal digit expected");
1810 data->type = REPL_TYPE_STRING;
1811 data->text = g_new0 (gchar, 8);
1812 g_unichar_to_utf8 (x, data->text);
1816 data->type = REPL_TYPE_CHANGE_CASE;
1817 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1821 data->type = REPL_TYPE_CHANGE_CASE;
1822 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1826 data->type = REPL_TYPE_CHANGE_CASE;
1827 data->change_case = CHANGE_CASE_LOWER;
1831 data->type = REPL_TYPE_CHANGE_CASE;
1832 data->change_case = CHANGE_CASE_UPPER;
1836 data->type = REPL_TYPE_CHANGE_CASE;
1837 data->change_case = CHANGE_CASE_NONE;
1843 error_detail = _("missing '<' in symbolic reference");
1852 error_detail = _("unfinished symbolic reference");
1859 error_detail = _("zero-length symbolic reference");
1862 if (g_ascii_isdigit (*q))
1867 h = g_ascii_digit_value (*q);
1870 error_detail = _("digit expected");
1879 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1886 if (!g_ascii_isalnum (*r))
1888 error_detail = _("illegal symbolic reference");
1895 data->text = g_strndup (q, p - q);
1896 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1901 /* if \0 is followed by a number is an octal number representing a
1902 * character, else it is a numeric reference. */
1903 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1906 p = g_utf8_next_char (p);
1919 for (i = 0; i < 3; i++)
1921 h = g_ascii_digit_value (*p);
1931 if (i == 2 && base == 10)
1937 if (base == 8 || i == 3)
1939 data->type = REPL_TYPE_STRING;
1940 data->text = g_new0 (gchar, 8);
1941 g_unichar_to_utf8 (x, data->text);
1945 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1950 error_detail = _("stray final '\\'");
1954 error_detail = _("unknown escape sequence");
1961 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1962 tmp_error = g_error_new (G_REGEX_ERROR,
1963 G_REGEX_ERROR_REPLACE,
1964 _("Error while parsing replacement "
1965 "text \"%s\" at char %lu: %s"),
1967 (gulong)(p - replacement),
1969 g_propagate_error (error, tmp_error);
1975 split_replacement (const gchar *replacement,
1979 InterpolationData *data;
1980 const gchar *p, *start;
1982 start = p = replacement;
1987 data = g_new0 (InterpolationData, 1);
1988 start = p = expand_escape (replacement, p, data, error);
1991 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1993 free_interpolation_data (data);
1997 list = g_list_prepend (list, data);
2002 if (*p == '\\' || *p == '\0')
2006 data = g_new0 (InterpolationData, 1);
2007 data->text = g_strndup (start, p - start);
2008 data->type = REPL_TYPE_STRING;
2009 list = g_list_prepend (list, data);
2015 return g_list_reverse (list);
2018 /* Change the case of c based on change_case. */
2019 #define CHANGE_CASE(c, change_case) \
2020 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2021 g_unichar_tolower (c) : \
2022 g_unichar_toupper (c))
2025 string_append (GString *string,
2027 ChangeCase *change_case)
2031 if (text[0] == '\0')
2034 if (*change_case == CHANGE_CASE_NONE)
2036 g_string_append (string, text);
2038 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2040 c = g_utf8_get_char (text);
2041 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2042 g_string_append (string, g_utf8_next_char (text));
2043 *change_case = CHANGE_CASE_NONE;
2047 while (*text != '\0')
2049 c = g_utf8_get_char (text);
2050 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2051 text = g_utf8_next_char (text);
2057 interpolate_replacement (const GMatchInfo *match_info,
2062 InterpolationData *idata;
2064 ChangeCase change_case = CHANGE_CASE_NONE;
2066 for (list = data; list; list = list->next)
2069 switch (idata->type)
2071 case REPL_TYPE_STRING:
2072 string_append (result, idata->text, &change_case);
2074 case REPL_TYPE_CHARACTER:
2075 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2076 if (change_case & CHANGE_CASE_SINGLE_MASK)
2077 change_case = CHANGE_CASE_NONE;
2079 case REPL_TYPE_NUMERIC_REFERENCE:
2080 match = g_match_info_fetch (match_info, idata->num);
2083 string_append (result, match, &change_case);
2087 case REPL_TYPE_SYMBOLIC_REFERENCE:
2088 match = g_match_info_fetch_named (match_info, idata->text);
2091 string_append (result, match, &change_case);
2095 case REPL_TYPE_CHANGE_CASE:
2096 change_case = idata->change_case;
2104 /* whether actual match_info is needed for replacement, i.e.
2105 * whether there are references
2108 interpolation_list_needs_match (GList *list)
2110 while (list != NULL)
2112 InterpolationData *data = list->data;
2114 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2115 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2128 * @regex: a #GRegex structure
2129 * @string: the string to perform matches against
2130 * @string_len: the length of @string, or -1 if @string is nul-terminated
2131 * @start_position: starting index of the string to match
2132 * @replacement: text to replace each match with
2133 * @match_options: options for the match
2134 * @error: location to store the error occuring, or %NULL to ignore errors
2136 * Replaces all occurances of the pattern in @regex with the
2137 * replacement text. Backreferences of the form '\number' or
2138 * '\g<number>' in the replacement text are interpolated by the
2139 * number-th captured subexpression of the match, '\g<name>' refers
2140 * to the captured subexpression with the given name. '\0' refers to the
2141 * complete match, but '\0' followed by a number is the octal representation
2142 * of a character. To include a literal '\' in the replacement, write '\\'.
2143 * There are also escapes that changes the case of the following text:
2146 * <varlistentry><term>\l</term>
2148 * <para>Convert to lower case the next character</para>
2151 * <varlistentry><term>\u</term>
2153 * <para>Convert to upper case the next character</para>
2156 * <varlistentry><term>\L</term>
2158 * <para>Convert to lower case till \E</para>
2161 * <varlistentry><term>\U</term>
2163 * <para>Convert to upper case till \E</para>
2166 * <varlistentry><term>\E</term>
2168 * <para>End case modification</para>
2173 * If you do not need to use backreferences use g_regex_replace_literal().
2175 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2176 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2177 * you can use g_regex_replace_literal().
2179 * Setting @start_position differs from just passing over a shortened
2180 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2181 * begins with any kind of lookbehind assertion, such as "\b".
2183 * Returns: a newly allocated string containing the replacements
2188 g_regex_replace (const GRegex *regex,
2189 const gchar *string,
2191 gint start_position,
2192 const gchar *replacement,
2193 GRegexMatchFlags match_options,
2198 GError *tmp_error = NULL;
2200 g_return_val_if_fail (regex != NULL, NULL);
2201 g_return_val_if_fail (string != NULL, NULL);
2202 g_return_val_if_fail (start_position >= 0, NULL);
2203 g_return_val_if_fail (replacement != NULL, NULL);
2204 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2205 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2207 list = split_replacement (replacement, &tmp_error);
2208 if (tmp_error != NULL)
2210 g_propagate_error (error, tmp_error);
2214 result = g_regex_replace_eval (regex,
2215 string, string_len, start_position,
2217 interpolate_replacement,
2220 if (tmp_error != NULL)
2221 g_propagate_error (error, tmp_error);
2223 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2230 literal_replacement (const GMatchInfo *match_info,
2234 g_string_append (result, data);
2239 * g_regex_replace_literal:
2240 * @regex: a #GRegex structure
2241 * @string: the string to perform matches against
2242 * @string_len: the length of @string, or -1 if @string is nul-terminated
2243 * @start_position: starting index of the string to match
2244 * @replacement: text to replace each match with
2245 * @match_options: options for the match
2246 * @error: location to store the error occuring, or %NULL to ignore errors
2248 * Replaces all occurances of the pattern in @regex with the
2249 * replacement text. @replacement is replaced literally, to
2250 * include backreferences use g_regex_replace().
2252 * Setting @start_position differs from just passing over a
2253 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2254 * case of a pattern that begins with any kind of lookbehind
2255 * assertion, such as "\b".
2257 * Returns: a newly allocated string containing the replacements
2262 g_regex_replace_literal (const GRegex *regex,
2263 const gchar *string,
2265 gint start_position,
2266 const gchar *replacement,
2267 GRegexMatchFlags match_options,
2270 g_return_val_if_fail (replacement != NULL, NULL);
2271 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2273 return g_regex_replace_eval (regex,
2274 string, string_len, start_position,
2276 literal_replacement,
2277 (gpointer)replacement,
2282 * g_regex_replace_eval:
2283 * @regex: a #GRegex structure from g_regex_new()
2284 * @string: string to perform matches against
2285 * @string_len: the length of @string, or -1 if @string is nul-terminated
2286 * @start_position: starting index of the string to match
2287 * @match_options: options for the match
2288 * @eval: a function to call for each match
2289 * @user_data: user data to pass to the function
2290 * @error: location to store the error occuring, or %NULL to ignore errors
2292 * Replaces occurances of the pattern in regex with the output of
2293 * @eval for that occurance.
2295 * Setting @start_position differs from just passing over a shortened
2296 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2297 * that begins with any kind of lookbehind assertion, such as "\b".
2299 * Returns: a newly allocated string containing the replacements
2304 g_regex_replace_eval (const GRegex *regex,
2305 const gchar *string,
2307 gint start_position,
2308 GRegexMatchFlags match_options,
2309 GRegexEvalCallback eval,
2313 GMatchInfo *match_info;
2316 gboolean done = FALSE;
2317 GError *tmp_error = NULL;
2319 g_return_val_if_fail (regex != NULL, NULL);
2320 g_return_val_if_fail (string != NULL, NULL);
2321 g_return_val_if_fail (start_position >= 0, NULL);
2322 g_return_val_if_fail (eval != NULL, NULL);
2323 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2326 string_len = strlen (string);
2328 result = g_string_sized_new (string_len);
2330 /* run down the string making matches. */
2331 g_regex_match_full (regex, string, string_len, start_position,
2332 match_options, &match_info, &tmp_error);
2333 while (!done && g_match_info_matches (match_info))
2335 g_string_append_len (result,
2337 match_info->offsets[0] - str_pos);
2338 done = (*eval) (match_info, result, user_data);
2339 str_pos = match_info->offsets[1];
2340 g_match_info_next (match_info, &tmp_error);
2342 g_match_info_free (match_info);
2343 if (tmp_error != NULL)
2345 g_propagate_error (error, tmp_error);
2346 g_string_free (result, TRUE);
2350 g_string_append_len (result, string + str_pos, string_len - str_pos);
2351 return g_string_free (result, FALSE);
2355 * g_regex_check_replacement:
2356 * @replacement: the replacement string
2357 * @has_references: location to store information about
2358 * references in @replacement or %NULL
2359 * @error: location to store error
2361 * Checks whether @replacement is a valid replacement string
2362 * (see g_regex_replace()), i.e. that all escape sequences in
2365 * If @has_references is not %NULL then @replacement is checked
2366 * for pattern references. For instance, replacement text 'foo\n'
2367 * does not contain references and may be evaluated without information
2368 * about actual match, but '\0\1' (whole match followed by first
2369 * subpattern) requires valid #GMatchInfo object.
2371 * Returns: whether @replacement is a valid replacement string
2376 g_regex_check_replacement (const gchar *replacement,
2377 gboolean *has_references,
2383 list = split_replacement (replacement, &tmp);
2387 g_propagate_error (error, tmp);
2392 *has_references = interpolation_list_needs_match (list);
2394 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2401 * g_regex_escape_string:
2402 * @string: the string to escape
2403 * @length: the length of @string, or -1 if @string is nul-terminated
2405 * Escapes the special characters used for regular expressions
2406 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2407 * function is useful to dynamically generate regular expressions.
2409 * @string can contain nul characters that are replaced with "\0",
2410 * in this case remember to specify the correct length of @string
2413 * Returns: a newly-allocated escaped string
2418 g_regex_escape_string (const gchar *string,
2422 const char *p, *piece_start, *end;
2424 g_return_val_if_fail (string != NULL, NULL);
2427 length = strlen (string);
2429 end = string + length;
2430 p = piece_start = string;
2431 escaped = g_string_sized_new (length + 1);
2452 if (p != piece_start)
2453 /* copy the previous piece. */
2454 g_string_append_len (escaped, piece_start, p - piece_start);
2455 g_string_append_c (escaped, '\\');
2457 g_string_append_c (escaped, '0');
2459 g_string_append_c (escaped, *p);
2463 p = g_utf8_next_char (p);
2468 if (piece_start < end)
2469 g_string_append_len (escaped, piece_start, end - piece_start);
2471 return g_string_free (escaped, FALSE);
2474 #define __G_REGEX_C__
2475 #include "galiasdef.c"