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,
301 g_return_val_if_fail (match_info != NULL, FALSE);
302 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
303 g_return_val_if_fail (match_info->pos >= 0, FALSE);
305 opts = match_info->regex->match_opts | match_info->match_opts;
307 match_info->matches = pcre_exec (match_info->regex->pcre_re,
308 match_info->regex->extra,
310 match_info->string_len,
312 match_info->regex->match_opts |
313 match_info->match_opts,
315 match_info->n_offsets);
316 if (IS_PCRE_ERROR (match_info->matches))
318 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
319 _("Error while matching regular expression %s: %s"),
320 match_info->regex->pattern, match_error (match_info->matches));
324 /* avoid infinite loops if the pattern is an empty string or something
326 if (match_info->pos == match_info->offsets[1])
328 if (match_info->pos > match_info->string_len)
330 /* we have reached the end of the string */
331 match_info->pos = -1;
332 match_info->matches = PCRE_ERROR_NOMATCH;
336 match_info->pos = NEXT_CHAR (match_info->regex,
337 &match_info->string[match_info->pos]) -
342 match_info->pos = match_info->offsets[1];
345 return match_info->matches >= 0;
349 * g_match_info_matches:
350 * @match_info: a #GMatchInfo structure
352 * Returns whether the previous match operation succeeded.
354 * Returns: %TRUE if the previous match operation succeeded,
360 g_match_info_matches (const GMatchInfo *match_info)
362 g_return_val_if_fail (match_info != NULL, FALSE);
364 return match_info->matches >= 0;
368 * g_match_info_get_match_count:
369 * @match_info: a #GMatchInfo structure
371 * Retrieves the number of matched substrings (including substring 0,
372 * that is the whole matched text), so 1 is returned if the pattern
373 * has no substrings in it and 0 is returned if the match failed.
375 * If the last match was obtained using the DFA algorithm, that is
376 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
377 * count is not that of the number of capturing parentheses but that of
378 * the number of matched substrings.
380 * Returns: Number of matched substrings, or -1 if an error occurred
385 g_match_info_get_match_count (const GMatchInfo *match_info)
387 g_return_val_if_fail (match_info, -1);
389 if (match_info->matches == PCRE_ERROR_NOMATCH)
392 else if (match_info->matches < PCRE_ERROR_NOMATCH)
397 return match_info->matches;
401 * g_match_info_is_partial_match:
402 * @match_info: a #GMatchInfo structure
404 * Usually if the string passed to g_regex_match*() matches as far as
405 * it goes, but is too short to match the entire pattern, %FALSE is
406 * returned. There are circumstances where it might be helpful to
407 * distinguish this case from other cases in which there is no match.
409 * Consider, for example, an application where a human is required to
410 * type in data for a field with specific formatting requirements. An
411 * example might be a date in the form ddmmmyy, defined by the pattern
412 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
413 * If the application sees the user’s keystrokes one by one, and can
414 * check that what has been typed so far is potentially valid, it is
415 * able to raise an error as soon as a mistake is made.
417 * GRegex supports the concept of partial matching by means of the
418 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
419 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
420 * for a complete match, %FALSE otherwise. But, when these functions
421 * return %FALSE, you can check if the match was partial calling
422 * g_match_info_is_partial_match().
424 * When using partial matching you cannot use g_match_info_fetch*().
426 * Because of the way certain internal optimizations are implemented
427 * the partial matching algorithm cannot be used with all patterns.
428 * So repeated single characters such as "a{2,4}" and repeated single
429 * meta-sequences such as "\d+" are not permitted if the maximum number
430 * of occurrences is greater than one. Optional items such as "\d?"
431 * (where the maximum is one) are permitted. Quantifiers with any values
432 * are permitted after parentheses, so the invalid examples above can be
433 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
434 * for a pattern that does not conform to the restrictions, matching
435 * functions return an error.
437 * Returns: %TRUE if the match was partial, %FALSE otherwise
442 g_match_info_is_partial_match (const GMatchInfo *match_info)
444 g_return_val_if_fail (match_info != NULL, FALSE);
446 return match_info->matches == PCRE_ERROR_PARTIAL;
450 * g_match_info_expand_references:
451 * @match_info: a #GMatchInfo or %NULL
452 * @string_to_expand: the string to expand
453 * @error: location to store the error occuring, or %NULL to ignore errors
455 * Returns a new string containing the text in @string_to_expand with
456 * references and escape sequences expanded. References refer to the last
457 * match done with @string against @regex and have the same syntax used by
460 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
461 * passed to g_regex_new().
463 * The backreferences are extracted from the string passed to the match
464 * function, so you cannot call this function after freeing the string.
466 * @match_info may be %NULL in which case @string_to_expand must not
467 * contain references. For instance "foo\n" does not refer to an actual
468 * pattern and '\n' merely will be replaced with \n character,
469 * while to expand "\0" (whole match) one needs the result of a match.
470 * Use g_regex_check_replacement() to find out whether @string_to_expand
471 * contains references.
473 * Returns: the expanded string, or %NULL if an error occurred
478 g_match_info_expand_references (const GMatchInfo *match_info,
479 const gchar *string_to_expand,
484 GError *tmp_error = NULL;
486 g_return_val_if_fail (string_to_expand != NULL, NULL);
487 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
489 list = split_replacement (string_to_expand, &tmp_error);
490 if (tmp_error != NULL)
492 g_propagate_error (error, tmp_error);
496 if (!match_info && interpolation_list_needs_match (list))
498 g_critical ("String '%s' contains references to the match, can't "
499 "expand references without GMatchInfo object",
504 result = g_string_sized_new (strlen (string_to_expand));
505 interpolate_replacement (match_info, result, list);
507 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
510 return g_string_free (result, FALSE);
514 * g_match_info_fetch:
515 * @match_info: #GMatchInfo structure
516 * @match_num: number of the sub expression
518 * Retrieves the text matching the @match_num<!-- -->'th capturing
519 * parentheses. 0 is the full text of the match, 1 is the first paren
520 * set, 2 the second, and so on.
522 * If @match_num is a valid sub pattern but it didn't match anything
523 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
524 * string is returned.
526 * If the match was obtained using the DFA algorithm, that is using
527 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
528 * string is not that of a set of parentheses but that of a matched
529 * substring. Substrings are matched in reverse order of length, so
530 * 0 is the longest match.
532 * The string is fetched from the string passed to the match function,
533 * so you cannot call this function after freeing the string.
535 * Returns: The matched substring, or %NULL if an error occurred.
536 * You have to free the string yourself
541 g_match_info_fetch (const GMatchInfo *match_info,
544 /* we cannot use pcre_get_substring() because it allocates the
545 * string using pcre_malloc(). */
549 g_return_val_if_fail (match_info != NULL, NULL);
550 g_return_val_if_fail (match_num >= 0, NULL);
552 /* match_num does not exist or it didn't matched, i.e. matching "b"
553 * against "(a)?b" then group 0 is empty. */
554 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
556 else if (start == -1)
557 match = g_strdup ("");
559 match = g_strndup (&match_info->string[start], end - start);
565 * g_match_info_fetch_pos:
566 * @match_info: #GMatchInfo structure
567 * @match_num: number of the sub expression
568 * @start_pos: pointer to location where to store the start position
569 * @end_pos: pointer to location where to store the end position
571 * Retrieves the position of the @match_num<!-- -->'th capturing
572 * parentheses. 0 is the full text of the match, 1 is the first
573 * paren set, 2 the second, and so on.
575 * If @match_num is a valid sub pattern but it didn't match anything
576 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
577 * and @end_pos are set to -1 and %TRUE is returned.
579 * If the match was obtained using the DFA algorithm, that is using
580 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
581 * position is not that of a set of parentheses but that of a matched
582 * substring. Substrings are matched in reverse order of length, so
583 * 0 is the longest match.
585 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
586 * the position cannot be fetched, @start_pos and @end_pos are left
592 g_match_info_fetch_pos (const GMatchInfo *match_info,
597 g_return_val_if_fail (match_info != NULL, FALSE);
598 g_return_val_if_fail (match_num >= 0, FALSE);
600 /* make sure the sub expression number they're requesting is less than
601 * the total number of sub expressions that were matched. */
602 if (match_num >= match_info->matches)
605 if (start_pos != NULL)
606 *start_pos = match_info->offsets[2 * match_num];
609 *end_pos = match_info->offsets[2 * match_num + 1];
615 * Returns number of first matched subpattern with name @name.
616 * There may be more than one in case when DUPNAMES is used,
617 * and not all subpatterns with that name match;
618 * pcre_get_stringnumber() does not work in that case.
621 get_matched_substring_number (const GMatchInfo *match_info,
629 * FIXME: (?J) may be used inside the pattern as the equivalent of
630 * DUPNAMES compile option. In this case we can't know about it,
631 * and pcre doesn't tell us about it either, it uses private flag
632 * PCRE_JCHANGED for this. So we have to always search string
633 * table, unlike pcre which uses pcre_get_stringnumber() shortcut
634 * when possible. It shouldn't be actually bad since
635 * pcre_get_stringtable_entries() uses binary search; still would
636 * be better to fix it, to be not worse than pcre.
639 if ((match_info->regex->compile_opts & G_REGEX_DUPNAMES) == 0)
640 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
643 /* This code is copied from pcre_get.c: get_first_set() */
644 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
652 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
654 gint n = (entry[0] << 8) + entry[1];
655 if (match_info->offsets[n*2] >= 0)
659 return (first[0] << 8) + first[1];
663 * g_match_info_fetch_named:
664 * @match_info: #GMatchInfo structure
665 * @name: name of the subexpression
667 * Retrieves the text matching the capturing parentheses named @name.
669 * If @name is a valid sub pattern name but it didn't match anything
670 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
671 * then an empty string is returned.
673 * The string is fetched from the string passed to the match function,
674 * so you cannot call this function after freeing the string.
676 * Returns: The matched substring, or %NULL if an error occurred.
677 * You have to free the string yourself
682 g_match_info_fetch_named (const GMatchInfo *match_info,
685 /* we cannot use pcre_get_named_substring() because it allocates the
686 * string using pcre_malloc(). */
689 g_return_val_if_fail (match_info != NULL, NULL);
690 g_return_val_if_fail (name != NULL, NULL);
692 num = get_matched_substring_number (match_info, name);
696 return g_match_info_fetch (match_info, num);
700 * g_match_info_fetch_named_pos:
701 * @match_info: #GMatchInfo structure
702 * @name: name of the subexpression
703 * @start_pos: pointer to location where to store the start position
704 * @end_pos: pointer to location where to store the end position
706 * Retrieves the position of the capturing parentheses named @name.
708 * If @name is a valid sub pattern name but it didn't match anything
709 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
710 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
712 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
713 * the position cannot be fetched, @start_pos and @end_pos are left
719 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
726 g_return_val_if_fail (match_info != NULL, FALSE);
727 g_return_val_if_fail (name != NULL, FALSE);
729 num = get_matched_substring_number (match_info, name);
733 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
737 * g_match_info_fetch_all:
738 * @match_info: a #GMatchInfo structure
740 * Bundles up pointers to each of the matching substrings from a match
741 * and stores them in an array of gchar pointers. The first element in
742 * the returned array is the match number 0, i.e. the entire matched
745 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
746 * "b" against "(a)?b") then an empty string is inserted.
748 * If the last match was obtained using the DFA algorithm, that is using
749 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
750 * strings are not that matched by sets of parentheses but that of the
751 * matched substring. Substrings are matched in reverse order of length,
752 * so the first one is the longest match.
754 * The strings are fetched from the string passed to the match function,
755 * so you cannot call this function after freeing the string.
757 * Returns: a %NULL-terminated array of gchar * pointers. It must be
758 * freed using g_strfreev(). If the previous match failed %NULL is
764 g_match_info_fetch_all (const GMatchInfo *match_info)
766 /* we cannot use pcre_get_substring_list() because the returned value
767 * isn't suitable for g_strfreev(). */
771 g_return_val_if_fail (match_info != NULL, FALSE);
773 if (match_info->matches < 0)
776 result = g_new (gchar *, match_info->matches + 1);
777 for (i = 0; i < match_info->matches; i++)
778 result[i] = g_match_info_fetch (match_info, i);
788 g_regex_error_quark (void)
790 static GQuark error_quark = 0;
792 if (error_quark == 0)
793 error_quark = g_quark_from_static_string ("g-regex-error-quark");
802 * Increases reference count of @regex by 1.
809 g_regex_ref (GRegex *regex)
811 g_return_val_if_fail (regex != NULL, NULL);
812 g_atomic_int_inc ((gint*) ®ex->ref_count);
820 * Decreases reference count of @regex by 1. When reference count drops
821 * to zero, it frees all the memory associated with the regex structure.
826 g_regex_unref (GRegex *regex)
828 g_return_if_fail (regex != NULL);
830 if (g_atomic_int_exchange_and_add ((gint *) ®ex->ref_count, -1) - 1 == 0)
832 g_free (regex->pattern);
833 if (regex->pcre_re != NULL)
834 pcre_free (regex->pcre_re);
835 if (regex->extra != NULL)
836 pcre_free (regex->extra);
843 * @pattern: the regular expression
844 * @compile_options: compile options for the regular expression
845 * @match_options: match options for the regular expression
846 * @error: return location for a #GError
848 * Compiles the regular expression to an internal form, and does
849 * the initial setup of the #GRegex structure.
851 * Returns: a #GRegex structure. Call g_regex_unref() when you
857 g_regex_new (const gchar *pattern,
858 GRegexCompileFlags compile_options,
859 GRegexMatchFlags match_options,
866 gboolean optimize = FALSE;
867 static gboolean initialized = FALSE;
869 g_return_val_if_fail (pattern != NULL, NULL);
870 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
871 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
872 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
879 pcre_config (PCRE_CONFIG_UTF8, &support);
882 msg = N_("PCRE library is compiled without UTF8 support");
884 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
888 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
891 msg = N_("PCRE library is compiled without UTF8 properties support");
893 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
900 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
901 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
902 if (compile_options & G_REGEX_OPTIMIZE)
905 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
906 * instead uses UTF-8 only if required with PCRE_UTF8. */
907 if (compile_options & G_REGEX_RAW)
910 compile_options &= ~G_REGEX_RAW;
915 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
916 match_options |= PCRE_NO_UTF8_CHECK;
919 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
920 * not for the system one. */
921 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
922 !(compile_options & G_REGEX_NEWLINE_LF))
924 compile_options |= PCRE_NEWLINE_ANY;
927 /* compile the pattern */
928 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
930 /* if the compilation failed, set the error member and return
934 GError *tmp_error = g_error_new (G_REGEX_ERROR,
935 G_REGEX_ERROR_COMPILE,
936 _("Error while compiling regular "
937 "expression %s at char %d: %s"),
938 pattern, erroffset, errmsg);
939 g_propagate_error (error, tmp_error);
944 regex = g_new0 (GRegex, 1);
945 regex->ref_count = 1;
946 regex->pattern = g_strdup (pattern);
948 regex->compile_opts = compile_options;
949 regex->match_opts = match_options;
953 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
956 GError *tmp_error = g_error_new (G_REGEX_ERROR,
957 G_REGEX_ERROR_OPTIMIZE,
958 _("Error while optimizing "
959 "regular expression %s: %s"),
962 g_propagate_error (error, tmp_error);
971 * g_regex_get_pattern:
972 * @regex: a #GRegex structure
974 * Gets the pattern string associated with @regex, i.e. a copy of
975 * the string passed to g_regex_new().
977 * Returns: the pattern of @regex
982 g_regex_get_pattern (const GRegex *regex)
984 g_return_val_if_fail (regex != NULL, NULL);
986 return regex->pattern;
990 * g_regex_get_max_backref:
993 * Returns the number of the highest back reference
994 * in the pattern, or 0 if the pattern does not contain
997 * Returns: the number of the highest back reference
1002 g_regex_get_max_backref (const GRegex *regex)
1006 pcre_fullinfo (regex->pcre_re, regex->extra,
1007 PCRE_INFO_BACKREFMAX, &value);
1013 * g_regex_get_capture_count:
1016 * Returns the number of capturing subpatterns in the pattern.
1018 * Returns: the number of capturing subpatterns
1023 g_regex_get_capture_count (const GRegex *regex)
1027 pcre_fullinfo (regex->pcre_re, regex->extra,
1028 PCRE_INFO_CAPTURECOUNT, &value);
1034 * g_regex_match_simple:
1035 * @pattern: the regular expression
1036 * @string: the string to scan for matches
1037 * @compile_options: compile options for the regular expression
1038 * @match_options: match options
1040 * Scans for a match in @string for @pattern.
1042 * This function is equivalent to g_regex_match() but it does not
1043 * require to compile the pattern with g_regex_new(), avoiding some
1044 * lines of code when you need just to do a match without extracting
1045 * substrings, capture counts, and so on.
1047 * If this function is to be called on the same @pattern more than
1048 * once, it's more efficient to compile the pattern once with
1049 * g_regex_new() and then use g_regex_match().
1051 * Returns: %TRUE is the string matched, %FALSE otherwise
1056 g_regex_match_simple (const gchar *pattern,
1057 const gchar *string,
1058 GRegexCompileFlags compile_options,
1059 GRegexMatchFlags match_options)
1064 regex = g_regex_new (pattern, compile_options, 0, NULL);
1067 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1068 g_regex_unref (regex);
1074 * @regex: a #GRegex structure from g_regex_new()
1075 * @string: the string to scan for matches
1076 * @match_options: match options
1077 * @match_info: pointer to location where to store the #GMatchInfo,
1078 * or %NULL if you do not need it
1080 * Scans for a match in string for the pattern in @regex.
1081 * The @match_options are combined with the match options specified
1082 * when the @regex structure was created, letting you have more
1083 * flexibility in reusing #GRegex structures.
1085 * A #GMatchInfo structure, used to get information on the match,
1086 * is stored in @match_info if not %NULL. Note that if @match_info
1087 * is not %NULL then it is created even if the function returns %FALSE,
1088 * i.e. you must free it regardless if regular expression actually matched.
1090 * To retrieve all the non-overlapping matches of the pattern in
1091 * string you can use g_match_info_next().
1093 * <informalexample><programlisting>
1095 * print_uppercase_words (const gchar *string)
1097 * /* Print all uppercase-only words. */
1099 * GMatchInfo *match_info;
1101 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1102 * g_regex_match (regex, string, 0, &match_info);
1103 * while (g_match_info_matches (match_info))
1105 * gchar *word = g_match_info_fetch (match_info, 0);
1106 * g_print ("Found: %s\n", word);
1108 * g_match_info_next (match_info, NULL);
1110 * g_match_info_free (match_info);
1111 * g_regex_unref (regex);
1113 * </programlisting></informalexample>
1115 * Returns: %TRUE is the string matched, %FALSE otherwise
1120 g_regex_match (const GRegex *regex,
1121 const gchar *string,
1122 GRegexMatchFlags match_options,
1123 GMatchInfo **match_info)
1125 return g_regex_match_full (regex, string, -1, 0, match_options,
1130 * g_regex_match_full:
1131 * @regex: a #GRegex structure from g_regex_new()
1132 * @string: the string to scan for matches
1133 * @string_len: the length of @string, or -1 if @string is nul-terminated
1134 * @start_position: starting index of the string to match
1135 * @match_options: match options
1136 * @match_info: pointer to location where to store the #GMatchInfo,
1137 * or %NULL if you do not need it
1138 * @error: location to store the error occuring, or %NULL to ignore errors
1140 * Scans for a match in string for the pattern in @regex.
1141 * The @match_options are combined with the match options specified
1142 * when the @regex structure was created, letting you have more
1143 * flexibility in reusing #GRegex structures.
1145 * Setting @start_position differs from just passing over a shortened
1146 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1147 * that begins with any kind of lookbehind assertion, such as "\b".
1149 * A #GMatchInfo structure, used to get information on the match, is
1150 * stored in @match_info if not %NULL. Note that if @match_info is
1151 * not %NULL then it is created even if the function returns %FALSE,
1152 * i.e. you must free it regardless if regular expression actually
1155 * @string is not copied and is used in #GMatchInfo internally. If
1156 * you use any #GMatchInfo method (except g_match_info_free()) after
1157 * freeing or modifying @string then the behaviour is undefined.
1159 * To retrieve all the non-overlapping matches of the pattern in
1160 * string you can use g_match_info_next().
1162 * <informalexample><programlisting>
1164 * print_uppercase_words (const gchar *string)
1166 * /* Print all uppercase-only words. */
1168 * GMatchInfo *match_info;
1169 * GError *error = NULL;
1171 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1172 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1173 * while (g_match_info_matches (match_info))
1175 * gchar *word = g_match_info_fetch (match_info, 0);
1176 * g_print ("Found: %s\n", word);
1178 * g_match_info_next (match_info, &error);
1180 * g_match_info_free (match_info);
1181 * g_regex_unref (regex);
1182 * if (error != NULL)
1184 * g_printerr ("Error while matching: %s\n", error->message);
1185 * g_error_free (error);
1188 * </programlisting></informalexample>
1190 * Returns: %TRUE is the string matched, %FALSE otherwise
1195 g_regex_match_full (const GRegex *regex,
1196 const gchar *string,
1198 gint start_position,
1199 GRegexMatchFlags match_options,
1200 GMatchInfo **match_info,
1206 g_return_val_if_fail (regex != NULL, FALSE);
1207 g_return_val_if_fail (string != NULL, FALSE);
1208 g_return_val_if_fail (start_position >= 0, FALSE);
1209 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1210 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1212 info = match_info_new (regex, string, string_len, start_position,
1213 match_options, FALSE);
1214 match_ok = g_match_info_next (info, error);
1215 if (match_info != NULL)
1218 g_match_info_free (info);
1224 * g_regex_match_all:
1225 * @regex: a #GRegex structure from g_regex_new()
1226 * @string: the string to scan for matches
1227 * @match_options: match options
1228 * @match_info: pointer to location where to store the #GMatchInfo,
1229 * or %NULL if you do not need it
1231 * Using the standard algorithm for regular expression matching only
1232 * the longest match in the string is retrieved. This function uses
1233 * a different algorithm so it can retrieve all the possible matches.
1234 * For more documentation see g_regex_match_all_full().
1236 * A #GMatchInfo structure, used to get information on the match, is
1237 * stored in @match_info if not %NULL. Note that if @match_info is
1238 * not %NULL then it is created even if the function returns %FALSE,
1239 * i.e. you must free it regardless if regular expression actually
1242 * Returns: %TRUE is the string matched, %FALSE otherwise
1247 g_regex_match_all (const GRegex *regex,
1248 const gchar *string,
1249 GRegexMatchFlags match_options,
1250 GMatchInfo **match_info)
1252 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1257 * g_regex_match_all_full:
1258 * @regex: a #GRegex structure from g_regex_new()
1259 * @string: the string to scan for matches
1260 * @string_len: the length of @string, or -1 if @string is nul-terminated
1261 * @start_position: starting index of the string to match
1262 * @match_options: match options
1263 * @match_info: pointer to location where to store the #GMatchInfo,
1264 * or %NULL if you do not need it
1265 * @error: location to store the error occuring, or %NULL to ignore errors
1267 * Using the standard algorithm for regular expression matching only
1268 * the longest match in the string is retrieved, it is not possibile
1269 * to obtain all the available matches. For instance matching
1270 * "<a> <b> <c>" against the pattern "<.*>"
1271 * you get "<a> <b> <c>".
1273 * This function uses a different algorithm (called DFA, i.e. deterministic
1274 * finite automaton), so it can retrieve all the possible matches, all
1275 * starting at the same point in the string. For instance matching
1276 * "<a> <b> <c>" against the pattern "<.*>"
1277 * you would obtain three matches: "<a> <b> <c>",
1278 * "<a> <b>" and "<a>".
1280 * The number of matched strings is retrieved using
1281 * g_match_info_get_match_count(). To obtain the matched strings and
1282 * their position you can use, respectively, g_match_info_fetch() and
1283 * g_match_info_fetch_pos(). Note that the strings are returned in
1284 * reverse order of length; that is, the longest matching string is
1287 * Note that the DFA algorithm is slower than the standard one and it
1288 * is not able to capture substrings, so backreferences do not work.
1290 * Setting @start_position differs from just passing over a shortened
1291 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1292 * that begins with any kind of lookbehind assertion, such as "\b".
1294 * A #GMatchInfo structure, used to get information on the match, is
1295 * stored in @match_info if not %NULL. Note that if @match_info is
1296 * not %NULL then it is created even if the function returns %FALSE,
1297 * i.e. you must free it regardless if regular expression actually
1300 * Returns: %TRUE is the string matched, %FALSE otherwise
1305 g_regex_match_all_full (const GRegex *regex,
1306 const gchar *string,
1308 gint start_position,
1309 GRegexMatchFlags match_options,
1310 GMatchInfo **match_info,
1316 g_return_val_if_fail (regex != NULL, FALSE);
1317 g_return_val_if_fail (string != NULL, FALSE);
1318 g_return_val_if_fail (start_position >= 0, FALSE);
1319 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1320 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1322 info = match_info_new (regex, string, string_len, start_position,
1323 match_options, TRUE);
1329 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1330 info->string, info->string_len,
1332 regex->match_opts | match_options,
1333 info->offsets, info->n_offsets,
1334 info->workspace, info->n_workspace);
1335 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1337 /* info->workspace is too small. */
1338 info->n_workspace *= 2;
1339 info->workspace = g_realloc (info->workspace,
1340 info->n_workspace * sizeof (gint));
1343 else if (info->matches == 0)
1345 /* info->offsets is too small. */
1346 info->n_offsets *= 2;
1347 info->offsets = g_realloc (info->offsets,
1348 info->n_offsets * sizeof (gint));
1351 else if (IS_PCRE_ERROR (info->matches))
1353 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1354 _("Error while matching regular expression %s: %s"),
1355 regex->pattern, match_error (info->matches));
1359 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1362 if (match_info != NULL)
1365 g_match_info_free (info);
1367 return info->matches >= 0;
1371 * g_regex_get_string_number:
1372 * @regex: #GRegex structure
1373 * @name: name of the subexpression
1375 * Retrieves the number of the subexpression named @name.
1377 * Returns: The number of the subexpression or -1 if @name
1383 g_regex_get_string_number (const GRegex *regex,
1388 g_return_val_if_fail (regex != NULL, -1);
1389 g_return_val_if_fail (name != NULL, -1);
1391 num = pcre_get_stringnumber (regex->pcre_re, name);
1392 if (num == PCRE_ERROR_NOSUBSTRING)
1399 * g_regex_split_simple:
1400 * @pattern: the regular expression
1401 * @string: the string to scan for matches
1402 * @compile_options: compile options for the regular expression
1403 * @match_options: match options
1405 * Breaks the string on the pattern, and returns an array of
1406 * the tokens. If the pattern contains capturing parentheses,
1407 * then the text for each of the substrings will also be returned.
1408 * If the pattern does not match anywhere in the string, then the
1409 * whole string is returned as the first token.
1411 * This function is equivalent to g_regex_split() but it does
1412 * not require to compile the pattern with g_regex_new(), avoiding
1413 * some lines of code when you need just to do a split without
1414 * extracting substrings, capture counts, and so on.
1416 * If this function is to be called on the same @pattern more than
1417 * once, it's more efficient to compile the pattern once with
1418 * g_regex_new() and then use g_regex_split().
1420 * As a special case, the result of splitting the empty string ""
1421 * is an empty vector, not a vector containing a single string.
1422 * The reason for this special case is that being able to represent
1423 * a empty vector is typically more useful than consistent handling
1424 * of empty elements. If you do need to represent empty elements,
1425 * you'll need to check for the empty string before calling this
1428 * A pattern that can match empty strings splits @string into
1429 * separate characters wherever it matches the empty string between
1430 * characters. For example splitting "ab c" using as a separator
1431 * "\s*", you will get "a", "b" and "c".
1433 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1438 g_regex_split_simple (const gchar *pattern,
1439 const gchar *string,
1440 GRegexCompileFlags compile_options,
1441 GRegexMatchFlags match_options)
1446 regex = g_regex_new (pattern, compile_options, 0, NULL);
1449 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1450 g_regex_unref (regex);
1456 * @regex: a #GRegex structure
1457 * @string: the string to split with the pattern
1458 * @match_options: match time option flags
1460 * Breaks the string on the pattern, and returns an array of the tokens.
1461 * If the pattern contains capturing parentheses, then the text for each
1462 * of the substrings will also be returned. If the pattern does not match
1463 * anywhere in the string, then the whole string is returned as the first
1466 * As a special case, the result of splitting the empty string "" is an
1467 * empty vector, not a vector containing a single string. The reason for
1468 * this special case is that being able to represent a empty vector is
1469 * typically more useful than consistent handling of empty elements. If
1470 * you do need to represent empty elements, you'll need to check for the
1471 * empty string before calling this function.
1473 * A pattern that can match empty strings splits @string into separate
1474 * characters wherever it matches the empty string between characters.
1475 * For example splitting "ab c" using as a separator "\s*", you will get
1478 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1483 g_regex_split (const GRegex *regex,
1484 const gchar *string,
1485 GRegexMatchFlags match_options)
1487 return g_regex_split_full (regex, string, -1, 0,
1488 match_options, 0, NULL);
1492 * g_regex_split_full:
1493 * @regex: a #GRegex structure
1494 * @string: the string to split with the pattern
1495 * @string_len: the length of @string, or -1 if @string is nul-terminated
1496 * @start_position: starting index of the string to match
1497 * @match_options: match time option flags
1498 * @max_tokens: the maximum number of tokens to split @string into.
1499 * If this is less than 1, the string is split completely
1500 * @error: return location for a #GError
1502 * Breaks the string on the pattern, and returns an array of the tokens.
1503 * If the pattern contains capturing parentheses, then the text for each
1504 * of the substrings will also be returned. If the pattern does not match
1505 * anywhere in the string, then the whole string is returned as the first
1508 * As a special case, the result of splitting the empty string "" is an
1509 * empty vector, not a vector containing a single string. The reason for
1510 * this special case is that being able to represent a empty vector is
1511 * typically more useful than consistent handling of empty elements. If
1512 * you do need to represent empty elements, you'll need to check for the
1513 * empty string before calling this function.
1515 * A pattern that can match empty strings splits @string into separate
1516 * characters wherever it matches the empty string between characters.
1517 * For example splitting "ab c" using as a separator "\s*", you will get
1520 * Setting @start_position differs from just passing over a shortened
1521 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1522 * that begins with any kind of lookbehind assertion, such as "\b".
1524 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1529 g_regex_split_full (const GRegex *regex,
1530 const gchar *string,
1532 gint start_position,
1533 GRegexMatchFlags match_options,
1537 GError *tmp_error = NULL;
1538 GMatchInfo *match_info;
1543 /* position of the last separator. */
1544 gint last_separator_end;
1545 /* was the last match 0 bytes long? */
1546 gboolean last_match_is_empty;
1547 /* the returned array of char **s */
1548 gchar **string_list;
1550 g_return_val_if_fail (regex != NULL, NULL);
1551 g_return_val_if_fail (string != NULL, NULL);
1552 g_return_val_if_fail (start_position >= 0, NULL);
1553 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1554 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1556 if (max_tokens <= 0)
1557 max_tokens = G_MAXINT;
1560 string_len = strlen (string);
1562 /* zero-length string */
1563 if (string_len - start_position == 0)
1564 return g_new0 (gchar *, 1);
1566 if (max_tokens == 1)
1568 string_list = g_new0 (gchar *, 2);
1569 string_list[0] = g_strndup (&string[start_position],
1570 string_len - start_position);
1576 last_separator_end = start_position;
1577 last_match_is_empty = FALSE;
1579 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1580 match_options, &match_info, &tmp_error);
1581 while (tmp_error == NULL)
1585 last_match_is_empty =
1586 (match_info->offsets[0] == match_info->offsets[1]);
1588 /* we need to skip empty separators at the same position of the end
1589 * of another separator. e.g. the string is "a b" and the separator
1590 * is " *", so from 1 to 2 we have a match and at position 2 we have
1591 * an empty match. */
1592 if (last_separator_end != match_info->offsets[1])
1597 token = g_strndup (string + last_separator_end,
1598 match_info->offsets[0] - last_separator_end);
1599 list = g_list_prepend (list, token);
1602 /* if there were substrings, these need to be added to
1604 match_count = g_match_info_get_match_count (match_info);
1605 if (match_count > 1)
1607 for (i = 1; i < match_count; i++)
1608 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1614 /* if there was no match, copy to end of string. */
1615 if (!last_match_is_empty)
1617 gchar *token = g_strndup (string + last_separator_end,
1618 match_info->string_len - last_separator_end);
1619 list = g_list_prepend (list, token);
1621 /* no more tokens, end the loop. */
1625 /* -1 to leave room for the last part. */
1626 if (token_count >= max_tokens - 1)
1628 /* we have reached the maximum number of tokens, so we copy
1629 * the remaining part of the string. */
1630 if (last_match_is_empty)
1632 /* the last match was empty, so we have moved one char
1633 * after the real position to avoid empty matches at the
1635 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1637 /* the if is needed in the case we have terminated the available
1638 * tokens, but we are at the end of the string, so there are no
1639 * characters left to copy. */
1640 if (string_len > match_info->pos)
1642 gchar *token = g_strndup (string + match_info->pos,
1643 string_len - match_info->pos);
1644 list = g_list_prepend (list, token);
1650 last_separator_end = match_info->pos;
1651 if (last_match_is_empty)
1652 /* if the last match was empty, g_match_info_next() has moved
1653 * forward to avoid infinite loops, but we still need to copy that
1655 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1657 match_ok = g_match_info_next (match_info, &tmp_error);
1659 g_match_info_free (match_info);
1660 if (tmp_error != NULL)
1662 g_propagate_error (error, tmp_error);
1663 g_list_foreach (list, (GFunc)g_free, NULL);
1665 match_info->pos = -1;
1669 string_list = g_new (gchar *, g_list_length (list) + 1);
1671 for (last = g_list_last (list); last; last = g_list_previous (last))
1672 string_list[i++] = last->data;
1682 REPL_TYPE_CHARACTER,
1683 REPL_TYPE_SYMBOLIC_REFERENCE,
1684 REPL_TYPE_NUMERIC_REFERENCE,
1685 REPL_TYPE_CHANGE_CASE
1690 CHANGE_CASE_NONE = 1 << 0,
1691 CHANGE_CASE_UPPER = 1 << 1,
1692 CHANGE_CASE_LOWER = 1 << 2,
1693 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1694 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1695 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1696 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1697 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1700 struct _InterpolationData
1706 ChangeCase change_case;
1710 free_interpolation_data (InterpolationData *data)
1712 g_free (data->text);
1716 static const gchar *
1717 expand_escape (const gchar *replacement,
1719 InterpolationData *data,
1724 const gchar *error_detail;
1726 GError *tmp_error = NULL;
1734 data->type = REPL_TYPE_CHARACTER;
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;
1779 h = g_ascii_xdigit_value (*p);
1782 error_detail = _("hexadecimal digit or '}' expected");
1793 for (i = 0; i < 2; i++)
1795 h = g_ascii_xdigit_value (*p);
1798 error_detail = _("hexadecimal digit expected");
1805 data->type = REPL_TYPE_STRING;
1806 data->text = g_new0 (gchar, 8);
1807 g_unichar_to_utf8 (x, data->text);
1811 data->type = REPL_TYPE_CHANGE_CASE;
1812 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1816 data->type = REPL_TYPE_CHANGE_CASE;
1817 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1821 data->type = REPL_TYPE_CHANGE_CASE;
1822 data->change_case = CHANGE_CASE_LOWER;
1826 data->type = REPL_TYPE_CHANGE_CASE;
1827 data->change_case = CHANGE_CASE_UPPER;
1831 data->type = REPL_TYPE_CHANGE_CASE;
1832 data->change_case = CHANGE_CASE_NONE;
1838 error_detail = _("missing '<' in symbolic reference");
1847 error_detail = _("unfinished symbolic reference");
1854 error_detail = _("zero-length symbolic reference");
1857 if (g_ascii_isdigit (*q))
1862 h = g_ascii_digit_value (*q);
1865 error_detail = _("digit expected");
1874 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1881 if (!g_ascii_isalnum (*r))
1883 error_detail = _("illegal symbolic reference");
1890 data->text = g_strndup (q, p - q);
1891 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1896 /* if \0 is followed by a number is an octal number representing a
1897 * character, else it is a numeric reference. */
1898 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1901 p = g_utf8_next_char (p);
1914 for (i = 0; i < 3; i++)
1916 h = g_ascii_digit_value (*p);
1926 if (i == 2 && base == 10)
1932 if (base == 8 || i == 3)
1934 data->type = REPL_TYPE_STRING;
1935 data->text = g_new0 (gchar, 8);
1936 g_unichar_to_utf8 (x, data->text);
1940 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1945 error_detail = _("stray final '\\'");
1949 error_detail = _("unknown escape sequence");
1956 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1957 tmp_error = g_error_new (G_REGEX_ERROR,
1958 G_REGEX_ERROR_REPLACE,
1959 _("Error while parsing replacement "
1960 "text \"%s\" at char %lu: %s"),
1962 (gulong)(p - replacement),
1964 g_propagate_error (error, tmp_error);
1970 split_replacement (const gchar *replacement,
1974 InterpolationData *data;
1975 const gchar *p, *start;
1977 start = p = replacement;
1982 data = g_new0 (InterpolationData, 1);
1983 start = p = expand_escape (replacement, p, data, error);
1986 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1988 free_interpolation_data (data);
1992 list = g_list_prepend (list, data);
1997 if (*p == '\\' || *p == '\0')
2001 data = g_new0 (InterpolationData, 1);
2002 data->text = g_strndup (start, p - start);
2003 data->type = REPL_TYPE_STRING;
2004 list = g_list_prepend (list, data);
2010 return g_list_reverse (list);
2013 /* Change the case of c based on change_case. */
2014 #define CHANGE_CASE(c, change_case) \
2015 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2016 g_unichar_tolower (c) : \
2017 g_unichar_toupper (c))
2020 string_append (GString *string,
2022 ChangeCase *change_case)
2026 if (text[0] == '\0')
2029 if (*change_case == CHANGE_CASE_NONE)
2031 g_string_append (string, text);
2033 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2035 c = g_utf8_get_char (text);
2036 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2037 g_string_append (string, g_utf8_next_char (text));
2038 *change_case = CHANGE_CASE_NONE;
2042 while (*text != '\0')
2044 c = g_utf8_get_char (text);
2045 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2046 text = g_utf8_next_char (text);
2052 interpolate_replacement (const GMatchInfo *match_info,
2057 InterpolationData *idata;
2059 ChangeCase change_case = CHANGE_CASE_NONE;
2061 for (list = data; list; list = list->next)
2064 switch (idata->type)
2066 case REPL_TYPE_STRING:
2067 string_append (result, idata->text, &change_case);
2069 case REPL_TYPE_CHARACTER:
2070 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2071 if (change_case & CHANGE_CASE_SINGLE_MASK)
2072 change_case = CHANGE_CASE_NONE;
2074 case REPL_TYPE_NUMERIC_REFERENCE:
2075 match = g_match_info_fetch (match_info, idata->num);
2078 string_append (result, match, &change_case);
2082 case REPL_TYPE_SYMBOLIC_REFERENCE:
2083 match = g_match_info_fetch_named (match_info, idata->text);
2086 string_append (result, match, &change_case);
2090 case REPL_TYPE_CHANGE_CASE:
2091 change_case = idata->change_case;
2099 /* whether actual match_info is needed for replacement, i.e.
2100 * whether there are references
2103 interpolation_list_needs_match (GList *list)
2105 while (list != NULL)
2107 InterpolationData *data = list->data;
2109 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2110 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2123 * @regex: a #GRegex structure
2124 * @string: the string to perform matches against
2125 * @string_len: the length of @string, or -1 if @string is nul-terminated
2126 * @start_position: starting index of the string to match
2127 * @replacement: text to replace each match with
2128 * @match_options: options for the match
2129 * @error: location to store the error occuring, or %NULL to ignore errors
2131 * Replaces all occurances of the pattern in @regex with the
2132 * replacement text. Backreferences of the form '\number' or
2133 * '\g<number>' in the replacement text are interpolated by the
2134 * number-th captured subexpression of the match, '\g<name>' refers
2135 * to the captured subexpression with the given name. '\0' refers to the
2136 * complete match, but '\0' followed by a number is the octal representation
2137 * of a character. To include a literal '\' in the replacement, write '\\'.
2138 * There are also escapes that changes the case of the following text:
2141 * <varlistentry><term>\l</term>
2143 * <para>Convert to lower case the next character</para>
2146 * <varlistentry><term>\u</term>
2148 * <para>Convert to upper case the next character</para>
2151 * <varlistentry><term>\L</term>
2153 * <para>Convert to lower case till \E</para>
2156 * <varlistentry><term>\U</term>
2158 * <para>Convert to upper case till \E</para>
2161 * <varlistentry><term>\E</term>
2163 * <para>End case modification</para>
2168 * If you do not need to use backreferences use g_regex_replace_literal().
2170 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2171 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2172 * you can use g_regex_replace_literal().
2174 * Setting @start_position differs from just passing over a shortened
2175 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2176 * begins with any kind of lookbehind assertion, such as "\b".
2178 * Returns: a newly allocated string containing the replacements
2183 g_regex_replace (const GRegex *regex,
2184 const gchar *string,
2186 gint start_position,
2187 const gchar *replacement,
2188 GRegexMatchFlags match_options,
2193 GError *tmp_error = NULL;
2195 g_return_val_if_fail (regex != NULL, NULL);
2196 g_return_val_if_fail (string != NULL, NULL);
2197 g_return_val_if_fail (start_position >= 0, NULL);
2198 g_return_val_if_fail (replacement != NULL, NULL);
2199 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2200 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2202 list = split_replacement (replacement, &tmp_error);
2203 if (tmp_error != NULL)
2205 g_propagate_error (error, tmp_error);
2209 result = g_regex_replace_eval (regex,
2210 string, string_len, start_position,
2212 interpolate_replacement,
2215 if (tmp_error != NULL)
2216 g_propagate_error (error, tmp_error);
2218 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2225 literal_replacement (const GMatchInfo *match_info,
2229 g_string_append (result, data);
2234 * g_regex_replace_literal:
2235 * @regex: a #GRegex structure
2236 * @string: the string to perform matches against
2237 * @string_len: the length of @string, or -1 if @string is nul-terminated
2238 * @start_position: starting index of the string to match
2239 * @replacement: text to replace each match with
2240 * @match_options: options for the match
2241 * @error: location to store the error occuring, or %NULL to ignore errors
2243 * Replaces all occurances of the pattern in @regex with the
2244 * replacement text. @replacement is replaced literally, to
2245 * include backreferences use g_regex_replace().
2247 * Setting @start_position differs from just passing over a
2248 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2249 * case of a pattern that begins with any kind of lookbehind
2250 * assertion, such as "\b".
2252 * Returns: a newly allocated string containing the replacements
2257 g_regex_replace_literal (const GRegex *regex,
2258 const gchar *string,
2260 gint start_position,
2261 const gchar *replacement,
2262 GRegexMatchFlags match_options,
2265 g_return_val_if_fail (replacement != NULL, NULL);
2266 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2268 return g_regex_replace_eval (regex,
2269 string, string_len, start_position,
2271 literal_replacement,
2272 (gpointer)replacement,
2277 * g_regex_replace_eval:
2278 * @regex: a #GRegex structure from g_regex_new()
2279 * @string: string to perform matches against
2280 * @string_len: the length of @string, or -1 if @string is nul-terminated
2281 * @start_position: starting index of the string to match
2282 * @match_options: options for the match
2283 * @eval: a function to call for each match
2284 * @user_data: user data to pass to the function
2285 * @error: location to store the error occuring, or %NULL to ignore errors
2287 * Replaces occurances of the pattern in regex with the output of
2288 * @eval for that occurance.
2290 * Setting @start_position differs from just passing over a shortened
2291 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2292 * that begins with any kind of lookbehind assertion, such as "\b".
2294 * Returns: a newly allocated string containing the replacements
2299 g_regex_replace_eval (const GRegex *regex,
2300 const gchar *string,
2302 gint start_position,
2303 GRegexMatchFlags match_options,
2304 GRegexEvalCallback eval,
2308 GMatchInfo *match_info;
2311 gboolean done = FALSE;
2312 GError *tmp_error = NULL;
2314 g_return_val_if_fail (regex != NULL, NULL);
2315 g_return_val_if_fail (string != NULL, NULL);
2316 g_return_val_if_fail (start_position >= 0, NULL);
2317 g_return_val_if_fail (eval != NULL, NULL);
2318 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2321 string_len = strlen (string);
2323 result = g_string_sized_new (string_len);
2325 /* run down the string making matches. */
2326 g_regex_match_full (regex, string, string_len, start_position,
2327 match_options, &match_info, &tmp_error);
2328 while (!done && g_match_info_matches (match_info))
2330 g_string_append_len (result,
2332 match_info->offsets[0] - str_pos);
2333 done = (*eval) (match_info, result, user_data);
2334 str_pos = match_info->offsets[1];
2335 g_match_info_next (match_info, &tmp_error);
2337 g_match_info_free (match_info);
2338 if (tmp_error != NULL)
2340 g_propagate_error (error, tmp_error);
2341 g_string_free (result, TRUE);
2345 g_string_append_len (result, string + str_pos, string_len - str_pos);
2346 return g_string_free (result, FALSE);
2350 * g_regex_check_replacement:
2351 * @replacement: the replacement string
2352 * @has_references: location to store information about
2353 * references in @replacement or %NULL
2354 * @error: location to store error
2356 * Checks whether @replacement is a valid replacement string
2357 * (see g_regex_replace()), i.e. that all escape sequences in
2360 * If @has_references is not %NULL then @replacement is checked
2361 * for pattern references. For instance, replacement text 'foo\n'
2362 * does not contain references and may be evaluated without information
2363 * about actual match, but '\0\1' (whole match followed by first
2364 * subpattern) requires valid #GMatchInfo object.
2366 * Returns: whether @replacement is a valid replacement string
2371 g_regex_check_replacement (const gchar *replacement,
2372 gboolean *has_references,
2378 list = split_replacement (replacement, &tmp);
2382 g_propagate_error (error, tmp);
2387 *has_references = interpolation_list_needs_match (list);
2389 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2396 * g_regex_escape_string:
2397 * @string: the string to escape
2398 * @length: the length of @string, or -1 if @string is nul-terminated
2400 * Escapes the special characters used for regular expressions
2401 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2402 * function is useful to dynamically generate regular expressions.
2404 * @string can contain nul characters that are replaced with "\0",
2405 * in this case remember to specify the correct length of @string
2408 * Returns: a newly-allocated escaped string
2413 g_regex_escape_string (const gchar *string,
2417 const char *p, *piece_start, *end;
2419 g_return_val_if_fail (string != NULL, NULL);
2422 length = strlen (string);
2424 end = string + length;
2425 p = piece_start = string;
2426 escaped = g_string_sized_new (length + 1);
2447 if (p != piece_start)
2448 /* copy the previous piece. */
2449 g_string_append_len (escaped, piece_start, p - piece_start);
2450 g_string_append_c (escaped, '\\');
2452 g_string_append_c (escaped, '0');
2454 g_string_append_c (escaped, *p);
2458 p = g_utf8_next_char (p);
2463 if (piece_start < end)
2464 g_string_append_len (escaped, piece_start, end - piece_start);
2466 return g_string_free (escaped, FALSE);
2469 #define __G_REGEX_C__
2470 #include "galiasdef.c"