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
30 #ifdef USE_SYSTEM_PCRE
33 #include "pcre/pcre.h"
36 /* PCRE 7.3 does not contain the definition of PCRE_ERROR_NULLWSLIMIT */
37 #ifndef PCRE_ERROR_NULLWSLIMIT
38 #define PCRE_ERROR_NULLWSLIMIT (-22)
43 /* Mask of all the possible values for GRegexCompileFlags. */
44 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
49 G_REGEX_DOLLAR_ENDONLY | \
52 G_REGEX_NO_AUTO_CAPTURE | \
55 G_REGEX_NEWLINE_CR | \
56 G_REGEX_NEWLINE_LF | \
59 /* Mask of all the possible values for GRegexMatchFlags. */
60 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
61 G_REGEX_MATCH_NOTBOL | \
62 G_REGEX_MATCH_NOTEOL | \
63 G_REGEX_MATCH_NOTEMPTY | \
64 G_REGEX_MATCH_PARTIAL | \
65 G_REGEX_MATCH_NEWLINE_CR | \
66 G_REGEX_MATCH_NEWLINE_LF | \
67 G_REGEX_MATCH_NEWLINE_CRLF | \
68 G_REGEX_MATCH_NEWLINE_ANY)
70 /* if the string is in UTF-8 use g_utf8_ functions, else use
72 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
73 g_utf8_next_char (s) : \
75 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
76 g_utf8_prev_char (s) : \
81 GRegex *regex; /* the regex */
82 GRegexMatchFlags match_opts; /* options used at match time on the regex */
83 gint matches; /* number of matching sub patterns */
84 gint pos; /* position in the string where last match left off */
85 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
86 gint n_offsets; /* number of offsets */
87 gint *workspace; /* workspace for pcre_dfa_exec() */
88 gint n_workspace; /* number of workspace elements */
89 const gchar *string; /* string passed to the match function */
90 gssize string_len; /* length of string */
95 volatile gint ref_count; /* the ref count for the immutable part */
96 gchar *pattern; /* the pattern */
97 pcre *pcre_re; /* compiled form of the pattern */
98 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
99 GRegexMatchFlags match_opts; /* options used at match time on the regex */
100 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
103 /* TRUE if ret is an error code, FALSE otherwise. */
104 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
106 typedef struct _InterpolationData InterpolationData;
107 static gboolean interpolation_list_needs_match (GList *list);
108 static gboolean interpolate_replacement (const GMatchInfo *match_info,
111 static GList *split_replacement (const gchar *replacement,
113 static void free_interpolation_data (InterpolationData *data);
117 match_error (gint errcode)
121 case PCRE_ERROR_NOMATCH:
124 case PCRE_ERROR_NULL:
125 /* NULL argument, this should not happen in GRegex */
126 g_warning ("A NULL argument was passed to PCRE");
128 case PCRE_ERROR_BADOPTION:
129 return "bad options";
130 case PCRE_ERROR_BADMAGIC:
131 return _("corrupted object");
132 case PCRE_ERROR_UNKNOWN_OPCODE:
133 return N_("internal error or corrupted object");
134 case PCRE_ERROR_NOMEMORY:
135 return _("out of memory");
136 case PCRE_ERROR_NOSUBSTRING:
137 /* not used by pcre_exec() */
139 case PCRE_ERROR_MATCHLIMIT:
140 return _("backtracking limit reached");
141 case PCRE_ERROR_CALLOUT:
142 /* callouts are not implemented */
144 case PCRE_ERROR_BADUTF8:
145 case PCRE_ERROR_BADUTF8_OFFSET:
146 /* we do not check if strings are valid */
148 case PCRE_ERROR_PARTIAL:
151 case PCRE_ERROR_BADPARTIAL:
152 return _("the pattern contains items not supported for partial matching");
153 case PCRE_ERROR_INTERNAL:
154 return _("internal error");
155 case PCRE_ERROR_BADCOUNT:
156 /* negative ovecsize, this should not happen in GRegex */
157 g_warning ("A negative ovecsize was passed to PCRE");
159 case PCRE_ERROR_DFA_UITEM:
160 return _("the pattern contains items not supported for partial matching");
161 case PCRE_ERROR_DFA_UCOND:
162 return _("back references as conditions are not supported for partial matching");
163 case PCRE_ERROR_DFA_UMLIMIT:
164 /* the match_field field is not used in GRegex */
166 case PCRE_ERROR_DFA_WSSIZE:
167 /* handled expanding the workspace */
169 case PCRE_ERROR_DFA_RECURSE:
170 case PCRE_ERROR_RECURSIONLIMIT:
171 return _("recursion limit reached");
172 case PCRE_ERROR_NULLWSLIMIT:
173 return _("workspace limit for empty substrings reached");
174 case PCRE_ERROR_BADNEWLINE:
175 return _("invalid combination of newline flags");
179 return _("unknown error");
186 match_info_new (const GRegex *regex,
193 GMatchInfo *match_info;
196 string_len = strlen (string);
198 match_info = g_new0 (GMatchInfo, 1);
199 match_info->regex = g_regex_ref ((GRegex *)regex);
200 match_info->string = string;
201 match_info->string_len = string_len;
202 match_info->matches = PCRE_ERROR_NOMATCH;
203 match_info->pos = start_position;
204 match_info->match_opts = match_options;
208 /* These values should be enough for most cases, if they are not
209 * enough g_regex_match_all_full() will expand them. */
210 match_info->n_offsets = 24;
211 match_info->n_workspace = 100;
212 match_info->workspace = g_new (gint, match_info->n_workspace);
217 pcre_fullinfo (regex->pcre_re, regex->extra,
218 PCRE_INFO_CAPTURECOUNT, &capture_count);
219 match_info->n_offsets = (capture_count + 1) * 3;
221 match_info->offsets = g_new0 (gint, match_info->n_offsets);
227 * g_match_info_get_regex:
228 * @match_info: a #GMatchInfo
230 * Returns #GRegex object used in @match_info. It belongs to Glib
231 * and must not be freed. Use g_regex_ref() if you need to keep it
232 * after you free @match_info object.
234 * Returns: #GRegex object used in @match_info
239 g_match_info_get_regex (const GMatchInfo *match_info)
241 g_return_val_if_fail (match_info != NULL, NULL);
242 return match_info->regex;
246 * g_match_info_get_string:
247 * @match_info: a #GMatchInfo
249 * Returns the string searched with @match_info. This is the
250 * string passed to g_regex_match() or g_regex_replace() so
251 * you may not free it before calling this function.
253 * Returns: the string searched with @match_info
258 g_match_info_get_string (const GMatchInfo *match_info)
260 g_return_val_if_fail (match_info != NULL, NULL);
261 return match_info->string;
266 * @match_info: a #GMatchInfo
268 * Frees all the memory associated with the #GMatchInfo structure.
273 g_match_info_free (GMatchInfo *match_info)
277 g_regex_unref (match_info->regex);
278 g_free (match_info->offsets);
279 g_free (match_info->workspace);
286 * @match_info: a #GMatchInfo structure
287 * @error: location to store the error occuring, or %NULL to ignore errors
289 * Scans for the next match using the same parameters of the previous
290 * call to g_regex_match_full() or g_regex_match() that returned
293 * The match is done on the string passed to the match function, so you
294 * cannot free it before calling this function.
296 * Returns: %TRUE is the string matched, %FALSE otherwise
301 g_match_info_next (GMatchInfo *match_info,
306 g_return_val_if_fail (match_info != NULL, FALSE);
307 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
308 g_return_val_if_fail (match_info->pos >= 0, FALSE);
310 opts = match_info->regex->match_opts | match_info->match_opts;
312 match_info->matches = pcre_exec (match_info->regex->pcre_re,
313 match_info->regex->extra,
315 match_info->string_len,
317 match_info->regex->match_opts |
318 match_info->match_opts,
320 match_info->n_offsets);
321 if (IS_PCRE_ERROR (match_info->matches))
323 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
324 _("Error while matching regular expression %s: %s"),
325 match_info->regex->pattern, match_error (match_info->matches));
329 /* avoid infinite loops if the pattern is an empty string or something
331 if (match_info->pos == match_info->offsets[1])
333 if (match_info->pos > match_info->string_len)
335 /* we have reached the end of the string */
336 match_info->pos = -1;
337 match_info->matches = PCRE_ERROR_NOMATCH;
341 match_info->pos = NEXT_CHAR (match_info->regex,
342 &match_info->string[match_info->pos]) -
347 match_info->pos = match_info->offsets[1];
350 return match_info->matches >= 0;
354 * g_match_info_matches:
355 * @match_info: a #GMatchInfo structure
357 * Returns whether the previous match operation succeeded.
359 * Returns: %TRUE if the previous match operation succeeded,
365 g_match_info_matches (const GMatchInfo *match_info)
367 g_return_val_if_fail (match_info != NULL, FALSE);
369 return match_info->matches >= 0;
373 * g_match_info_get_match_count:
374 * @match_info: a #GMatchInfo structure
376 * Retrieves the number of matched substrings (including substring 0,
377 * that is the whole matched text), so 1 is returned if the pattern
378 * has no substrings in it and 0 is returned if the match failed.
380 * If the last match was obtained using the DFA algorithm, that is
381 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
382 * count is not that of the number of capturing parentheses but that of
383 * the number of matched substrings.
385 * Returns: Number of matched substrings, or -1 if an error occurred
390 g_match_info_get_match_count (const GMatchInfo *match_info)
392 g_return_val_if_fail (match_info, -1);
394 if (match_info->matches == PCRE_ERROR_NOMATCH)
397 else if (match_info->matches < PCRE_ERROR_NOMATCH)
402 return match_info->matches;
406 * g_match_info_is_partial_match:
407 * @match_info: a #GMatchInfo structure
409 * Usually if the string passed to g_regex_match*() matches as far as
410 * it goes, but is too short to match the entire pattern, %FALSE is
411 * returned. There are circumstances where it might be helpful to
412 * distinguish this case from other cases in which there is no match.
414 * Consider, for example, an application where a human is required to
415 * type in data for a field with specific formatting requirements. An
416 * example might be a date in the form ddmmmyy, defined by the pattern
417 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
418 * If the application sees the user’s keystrokes one by one, and can
419 * check that what has been typed so far is potentially valid, it is
420 * able to raise an error as soon as a mistake is made.
422 * GRegex supports the concept of partial matching by means of the
423 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
424 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
425 * for a complete match, %FALSE otherwise. But, when these functions
426 * return %FALSE, you can check if the match was partial calling
427 * g_match_info_is_partial_match().
429 * When using partial matching you cannot use g_match_info_fetch*().
431 * Because of the way certain internal optimizations are implemented
432 * the partial matching algorithm cannot be used with all patterns.
433 * So repeated single characters such as "a{2,4}" and repeated single
434 * meta-sequences such as "\d+" are not permitted if the maximum number
435 * of occurrences is greater than one. Optional items such as "\d?"
436 * (where the maximum is one) are permitted. Quantifiers with any values
437 * are permitted after parentheses, so the invalid examples above can be
438 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
439 * for a pattern that does not conform to the restrictions, matching
440 * functions return an error.
442 * Returns: %TRUE if the match was partial, %FALSE otherwise
447 g_match_info_is_partial_match (const GMatchInfo *match_info)
449 g_return_val_if_fail (match_info != NULL, FALSE);
451 return match_info->matches == PCRE_ERROR_PARTIAL;
455 * g_match_info_expand_references:
456 * @match_info: a #GMatchInfo or %NULL
457 * @string_to_expand: the string to expand
458 * @error: location to store the error occuring, or %NULL to ignore errors
460 * Returns a new string containing the text in @string_to_expand with
461 * references and escape sequences expanded. References refer to the last
462 * match done with @string against @regex and have the same syntax used by
465 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
466 * passed to g_regex_new().
468 * The backreferences are extracted from the string passed to the match
469 * function, so you cannot call this function after freeing the string.
471 * @match_info may be %NULL in which case @string_to_expand must not
472 * contain references. For instance "foo\n" does not refer to an actual
473 * pattern and '\n' merely will be replaced with \n character,
474 * while to expand "\0" (whole match) one needs the result of a match.
475 * Use g_regex_check_replacement() to find out whether @string_to_expand
476 * contains references.
478 * Returns: the expanded string, or %NULL if an error occurred
483 g_match_info_expand_references (const GMatchInfo *match_info,
484 const gchar *string_to_expand,
489 GError *tmp_error = NULL;
491 g_return_val_if_fail (string_to_expand != NULL, NULL);
492 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
494 list = split_replacement (string_to_expand, &tmp_error);
495 if (tmp_error != NULL)
497 g_propagate_error (error, tmp_error);
501 if (!match_info && interpolation_list_needs_match (list))
503 g_critical ("String '%s' contains references to the match, can't "
504 "expand references without GMatchInfo object",
509 result = g_string_sized_new (strlen (string_to_expand));
510 interpolate_replacement (match_info, result, list);
512 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
515 return g_string_free (result, FALSE);
519 * g_match_info_fetch:
520 * @match_info: #GMatchInfo structure
521 * @match_num: number of the sub expression
523 * Retrieves the text matching the @match_num<!-- -->'th capturing
524 * parentheses. 0 is the full text of the match, 1 is the first paren
525 * set, 2 the second, and so on.
527 * If @match_num is a valid sub pattern but it didn't match anything
528 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
529 * string is returned.
531 * If the match was obtained using the DFA algorithm, that is using
532 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
533 * string is not that of a set of parentheses but that of a matched
534 * substring. Substrings are matched in reverse order of length, so
535 * 0 is the longest match.
537 * The string is fetched from the string passed to the match function,
538 * so you cannot call this function after freeing the string.
540 * Returns: The matched substring, or %NULL if an error occurred.
541 * You have to free the string yourself
546 g_match_info_fetch (const GMatchInfo *match_info,
549 /* we cannot use pcre_get_substring() because it allocates the
550 * string using pcre_malloc(). */
554 g_return_val_if_fail (match_info != NULL, NULL);
555 g_return_val_if_fail (match_num >= 0, NULL);
557 /* match_num does not exist or it didn't matched, i.e. matching "b"
558 * against "(a)?b" then group 0 is empty. */
559 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
561 else if (start == -1)
562 match = g_strdup ("");
564 match = g_strndup (&match_info->string[start], end - start);
570 * g_match_info_fetch_pos:
571 * @match_info: #GMatchInfo structure
572 * @match_num: number of the sub expression
573 * @start_pos: pointer to location where to store the start position
574 * @end_pos: pointer to location where to store the end position
576 * Retrieves the position of the @match_num<!-- -->'th capturing
577 * parentheses. 0 is the full text of the match, 1 is the first
578 * paren set, 2 the second, and so on.
580 * If @match_num is a valid sub pattern but it didn't match anything
581 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
582 * and @end_pos are set to -1 and %TRUE is returned.
584 * If the match was obtained using the DFA algorithm, that is using
585 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
586 * position is not that of a set of parentheses but that of a matched
587 * substring. Substrings are matched in reverse order of length, so
588 * 0 is the longest match.
590 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
591 * the position cannot be fetched, @start_pos and @end_pos are left
597 g_match_info_fetch_pos (const GMatchInfo *match_info,
602 g_return_val_if_fail (match_info != NULL, FALSE);
603 g_return_val_if_fail (match_num >= 0, FALSE);
605 /* make sure the sub expression number they're requesting is less than
606 * the total number of sub expressions that were matched. */
607 if (match_num >= match_info->matches)
610 if (start_pos != NULL)
611 *start_pos = match_info->offsets[2 * match_num];
614 *end_pos = match_info->offsets[2 * match_num + 1];
620 * Returns number of first matched subpattern with name @name.
621 * There may be more than one in case when DUPNAMES is used,
622 * and not all subpatterns with that name match;
623 * pcre_get_stringnumber() does not work in that case.
626 get_matched_substring_number (const GMatchInfo *match_info,
633 if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
634 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
636 /* This code is copied from pcre_get.c: get_first_set() */
637 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
645 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
647 gint n = (entry[0] << 8) + entry[1];
648 if (match_info->offsets[n*2] >= 0)
652 return (first[0] << 8) + first[1];
656 * g_match_info_fetch_named:
657 * @match_info: #GMatchInfo structure
658 * @name: name of the subexpression
660 * Retrieves the text matching the capturing parentheses named @name.
662 * If @name is a valid sub pattern name but it didn't match anything
663 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
664 * then an empty string is returned.
666 * The string is fetched from the string passed to the match function,
667 * so you cannot call this function after freeing the string.
669 * Returns: The matched substring, or %NULL if an error occurred.
670 * You have to free the string yourself
675 g_match_info_fetch_named (const GMatchInfo *match_info,
678 /* we cannot use pcre_get_named_substring() because it allocates the
679 * string using pcre_malloc(). */
682 g_return_val_if_fail (match_info != NULL, NULL);
683 g_return_val_if_fail (name != NULL, NULL);
685 num = get_matched_substring_number (match_info, name);
689 return g_match_info_fetch (match_info, num);
693 * g_match_info_fetch_named_pos:
694 * @match_info: #GMatchInfo structure
695 * @name: name of the subexpression
696 * @start_pos: pointer to location where to store the start position
697 * @end_pos: pointer to location where to store the end position
699 * Retrieves the position of the capturing parentheses named @name.
701 * If @name is a valid sub pattern name but it didn't match anything
702 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
703 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
705 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
706 * the position cannot be fetched, @start_pos and @end_pos are left
712 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
719 g_return_val_if_fail (match_info != NULL, FALSE);
720 g_return_val_if_fail (name != NULL, FALSE);
722 num = get_matched_substring_number (match_info, name);
726 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
730 * g_match_info_fetch_all:
731 * @match_info: a #GMatchInfo structure
733 * Bundles up pointers to each of the matching substrings from a match
734 * and stores them in an array of gchar pointers. The first element in
735 * the returned array is the match number 0, i.e. the entire matched
738 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
739 * "b" against "(a)?b") then an empty string is inserted.
741 * If the last match was obtained using the DFA algorithm, that is using
742 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
743 * strings are not that matched by sets of parentheses but that of the
744 * matched substring. Substrings are matched in reverse order of length,
745 * so the first one is the longest match.
747 * The strings are fetched from the string passed to the match function,
748 * so you cannot call this function after freeing the string.
750 * Returns: a %NULL-terminated array of gchar * pointers. It must be
751 * freed using g_strfreev(). If the previous match failed %NULL is
757 g_match_info_fetch_all (const GMatchInfo *match_info)
759 /* we cannot use pcre_get_substring_list() because the returned value
760 * isn't suitable for g_strfreev(). */
764 g_return_val_if_fail (match_info != NULL, NULL);
766 if (match_info->matches < 0)
769 result = g_new (gchar *, match_info->matches + 1);
770 for (i = 0; i < match_info->matches; i++)
771 result[i] = g_match_info_fetch (match_info, i);
781 g_regex_error_quark (void)
783 static GQuark error_quark = 0;
785 if (error_quark == 0)
786 error_quark = g_quark_from_static_string ("g-regex-error-quark");
795 * Increases reference count of @regex by 1.
802 g_regex_ref (GRegex *regex)
804 g_return_val_if_fail (regex != NULL, NULL);
805 g_atomic_int_inc (®ex->ref_count);
813 * Decreases reference count of @regex by 1. When reference count drops
814 * to zero, it frees all the memory associated with the regex structure.
819 g_regex_unref (GRegex *regex)
821 g_return_if_fail (regex != NULL);
823 if (g_atomic_int_exchange_and_add (®ex->ref_count, -1) - 1 == 0)
825 g_free (regex->pattern);
826 if (regex->pcre_re != NULL)
827 pcre_free (regex->pcre_re);
828 if (regex->extra != NULL)
829 pcre_free (regex->extra);
836 * @pattern: the regular expression
837 * @compile_options: compile options for the regular expression
838 * @match_options: match options for the regular expression
839 * @error: return location for a #GError
841 * Compiles the regular expression to an internal form, and does
842 * the initial setup of the #GRegex structure.
844 * Returns: a #GRegex structure. Call g_regex_unref() when you
850 g_regex_new (const gchar *pattern,
851 GRegexCompileFlags compile_options,
852 GRegexMatchFlags match_options,
859 gboolean optimize = FALSE;
860 static gboolean initialized = FALSE;
862 g_return_val_if_fail (pattern != NULL, NULL);
863 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
864 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
865 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
872 pcre_config (PCRE_CONFIG_UTF8, &support);
875 msg = N_("PCRE library is compiled without UTF8 support");
877 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
881 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
884 msg = N_("PCRE library is compiled without UTF8 properties support");
886 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
893 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
894 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
895 if (compile_options & G_REGEX_OPTIMIZE)
898 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
899 * instead uses UTF-8 only if required with PCRE_UTF8. */
900 if (compile_options & G_REGEX_RAW)
903 compile_options &= ~G_REGEX_RAW;
908 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
909 match_options |= PCRE_NO_UTF8_CHECK;
912 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
913 * not for the system one. */
914 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
915 !(compile_options & G_REGEX_NEWLINE_LF))
917 compile_options |= PCRE_NEWLINE_ANY;
920 /* compile the pattern */
921 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
923 /* if the compilation failed, set the error member and return
929 /* PCRE uses byte offsets but we want to show character offsets */
930 erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
932 tmp_error = g_error_new (G_REGEX_ERROR,
933 G_REGEX_ERROR_COMPILE,
934 _("Error while compiling regular "
935 "expression %s at char %d: %s"),
936 pattern, erroffset, errmsg);
937 g_propagate_error (error, tmp_error);
942 /* For options set at the beginning of the pattern, pcre puts them into
943 * compile options, e.g. "(?i)foo" will make the pcre structure store
944 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
945 pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &compile_options);
947 if (!(compile_options & G_REGEX_DUPNAMES))
949 gboolean jchanged = FALSE;
950 pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
952 compile_options |= G_REGEX_DUPNAMES;
955 regex = g_new0 (GRegex, 1);
956 regex->ref_count = 1;
957 regex->pattern = g_strdup (pattern);
959 regex->compile_opts = compile_options;
960 regex->match_opts = match_options;
964 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
967 GError *tmp_error = g_error_new (G_REGEX_ERROR,
968 G_REGEX_ERROR_OPTIMIZE,
969 _("Error while optimizing "
970 "regular expression %s: %s"),
973 g_propagate_error (error, tmp_error);
982 * g_regex_get_pattern:
983 * @regex: a #GRegex structure
985 * Gets the pattern string associated with @regex, i.e. a copy of
986 * the string passed to g_regex_new().
988 * Returns: the pattern of @regex
993 g_regex_get_pattern (const GRegex *regex)
995 g_return_val_if_fail (regex != NULL, NULL);
997 return regex->pattern;
1001 * g_regex_get_max_backref:
1004 * Returns the number of the highest back reference
1005 * in the pattern, or 0 if the pattern does not contain
1008 * Returns: the number of the highest back reference
1013 g_regex_get_max_backref (const GRegex *regex)
1017 pcre_fullinfo (regex->pcre_re, regex->extra,
1018 PCRE_INFO_BACKREFMAX, &value);
1024 * g_regex_get_capture_count:
1027 * Returns the number of capturing subpatterns in the pattern.
1029 * Returns: the number of capturing subpatterns
1034 g_regex_get_capture_count (const GRegex *regex)
1038 pcre_fullinfo (regex->pcre_re, regex->extra,
1039 PCRE_INFO_CAPTURECOUNT, &value);
1045 * g_regex_match_simple:
1046 * @pattern: the regular expression
1047 * @string: the string to scan for matches
1048 * @compile_options: compile options for the regular expression
1049 * @match_options: match options
1051 * Scans for a match in @string for @pattern.
1053 * This function is equivalent to g_regex_match() but it does not
1054 * require to compile the pattern with g_regex_new(), avoiding some
1055 * lines of code when you need just to do a match without extracting
1056 * substrings, capture counts, and so on.
1058 * If this function is to be called on the same @pattern more than
1059 * once, it's more efficient to compile the pattern once with
1060 * g_regex_new() and then use g_regex_match().
1062 * Returns: %TRUE is the string matched, %FALSE otherwise
1067 g_regex_match_simple (const gchar *pattern,
1068 const gchar *string,
1069 GRegexCompileFlags compile_options,
1070 GRegexMatchFlags match_options)
1075 regex = g_regex_new (pattern, compile_options, 0, NULL);
1078 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1079 g_regex_unref (regex);
1085 * @regex: a #GRegex structure from g_regex_new()
1086 * @string: the string to scan for matches
1087 * @match_options: match options
1088 * @match_info: pointer to location where to store the #GMatchInfo,
1089 * or %NULL if you do not need it
1091 * Scans for a match in string for the pattern in @regex.
1092 * The @match_options are combined with the match options specified
1093 * when the @regex structure was created, letting you have more
1094 * flexibility in reusing #GRegex structures.
1096 * A #GMatchInfo structure, used to get information on the match,
1097 * is stored in @match_info if not %NULL. Note that if @match_info
1098 * is not %NULL then it is created even if the function returns %FALSE,
1099 * i.e. you must free it regardless if regular expression actually matched.
1101 * To retrieve all the non-overlapping matches of the pattern in
1102 * string you can use g_match_info_next().
1104 * <informalexample><programlisting>
1106 * print_uppercase_words (const gchar *string)
1108 * /* Print all uppercase-only words. */
1110 * GMatchInfo *match_info;
1112 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1113 * g_regex_match (regex, string, 0, &match_info);
1114 * while (g_match_info_matches (match_info))
1116 * gchar *word = g_match_info_fetch (match_info, 0);
1117 * g_print ("Found: %s\n", word);
1119 * g_match_info_next (match_info, NULL);
1121 * g_match_info_free (match_info);
1122 * g_regex_unref (regex);
1124 * </programlisting></informalexample>
1126 * Returns: %TRUE is the string matched, %FALSE otherwise
1131 g_regex_match (const GRegex *regex,
1132 const gchar *string,
1133 GRegexMatchFlags match_options,
1134 GMatchInfo **match_info)
1136 return g_regex_match_full (regex, string, -1, 0, match_options,
1141 * g_regex_match_full:
1142 * @regex: a #GRegex structure from g_regex_new()
1143 * @string: the string to scan for matches
1144 * @string_len: the length of @string, or -1 if @string is nul-terminated
1145 * @start_position: starting index of the string to match
1146 * @match_options: match options
1147 * @match_info: pointer to location where to store the #GMatchInfo,
1148 * or %NULL if you do not need it
1149 * @error: location to store the error occuring, or %NULL to ignore errors
1151 * Scans for a match in string for the pattern in @regex.
1152 * The @match_options are combined with the match options specified
1153 * when the @regex structure was created, letting you have more
1154 * flexibility in reusing #GRegex structures.
1156 * Setting @start_position differs from just passing over a shortened
1157 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1158 * that begins with any kind of lookbehind assertion, such as "\b".
1160 * A #GMatchInfo structure, used to get information on the match, is
1161 * stored in @match_info if not %NULL. Note that if @match_info is
1162 * not %NULL then it is created even if the function returns %FALSE,
1163 * i.e. you must free it regardless if regular expression actually
1166 * @string is not copied and is used in #GMatchInfo internally. If
1167 * you use any #GMatchInfo method (except g_match_info_free()) after
1168 * freeing or modifying @string then the behaviour is undefined.
1170 * To retrieve all the non-overlapping matches of the pattern in
1171 * string you can use g_match_info_next().
1173 * <informalexample><programlisting>
1175 * print_uppercase_words (const gchar *string)
1177 * /* Print all uppercase-only words. */
1179 * GMatchInfo *match_info;
1180 * GError *error = NULL;
1182 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1183 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1184 * while (g_match_info_matches (match_info))
1186 * gchar *word = g_match_info_fetch (match_info, 0);
1187 * g_print ("Found: %s\n", word);
1189 * g_match_info_next (match_info, &error);
1191 * g_match_info_free (match_info);
1192 * g_regex_unref (regex);
1193 * if (error != NULL)
1195 * g_printerr ("Error while matching: %s\n", error->message);
1196 * g_error_free (error);
1199 * </programlisting></informalexample>
1201 * Returns: %TRUE is the string matched, %FALSE otherwise
1206 g_regex_match_full (const GRegex *regex,
1207 const gchar *string,
1209 gint start_position,
1210 GRegexMatchFlags match_options,
1211 GMatchInfo **match_info,
1217 g_return_val_if_fail (regex != NULL, FALSE);
1218 g_return_val_if_fail (string != NULL, FALSE);
1219 g_return_val_if_fail (start_position >= 0, FALSE);
1220 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1221 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1223 info = match_info_new (regex, string, string_len, start_position,
1224 match_options, FALSE);
1225 match_ok = g_match_info_next (info, error);
1226 if (match_info != NULL)
1229 g_match_info_free (info);
1235 * g_regex_match_all:
1236 * @regex: a #GRegex structure from g_regex_new()
1237 * @string: the string to scan for matches
1238 * @match_options: match options
1239 * @match_info: pointer to location where to store the #GMatchInfo,
1240 * or %NULL if you do not need it
1242 * Using the standard algorithm for regular expression matching only
1243 * the longest match in the string is retrieved. This function uses
1244 * a different algorithm so it can retrieve all the possible matches.
1245 * For more documentation see g_regex_match_all_full().
1247 * A #GMatchInfo structure, used to get information on the match, is
1248 * stored in @match_info if not %NULL. Note that if @match_info is
1249 * not %NULL then it is created even if the function returns %FALSE,
1250 * i.e. you must free it regardless if regular expression actually
1253 * Returns: %TRUE is the string matched, %FALSE otherwise
1258 g_regex_match_all (const GRegex *regex,
1259 const gchar *string,
1260 GRegexMatchFlags match_options,
1261 GMatchInfo **match_info)
1263 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1268 * g_regex_match_all_full:
1269 * @regex: a #GRegex structure from g_regex_new()
1270 * @string: the string to scan for matches
1271 * @string_len: the length of @string, or -1 if @string is nul-terminated
1272 * @start_position: starting index of the string to match
1273 * @match_options: match options
1274 * @match_info: pointer to location where to store the #GMatchInfo,
1275 * or %NULL if you do not need it
1276 * @error: location to store the error occuring, or %NULL to ignore errors
1278 * Using the standard algorithm for regular expression matching only
1279 * the longest match in the string is retrieved, it is not possibile
1280 * to obtain all the available matches. For instance matching
1281 * "<a> <b> <c>" against the pattern "<.*>"
1282 * you get "<a> <b> <c>".
1284 * This function uses a different algorithm (called DFA, i.e. deterministic
1285 * finite automaton), so it can retrieve all the possible matches, all
1286 * starting at the same point in the string. For instance matching
1287 * "<a> <b> <c>" against the pattern "<.*>"
1288 * you would obtain three matches: "<a> <b> <c>",
1289 * "<a> <b>" and "<a>".
1291 * The number of matched strings is retrieved using
1292 * g_match_info_get_match_count(). To obtain the matched strings and
1293 * their position you can use, respectively, g_match_info_fetch() and
1294 * g_match_info_fetch_pos(). Note that the strings are returned in
1295 * reverse order of length; that is, the longest matching string is
1298 * Note that the DFA algorithm is slower than the standard one and it
1299 * is not able to capture substrings, so backreferences do not work.
1301 * Setting @start_position differs from just passing over a shortened
1302 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1303 * that begins with any kind of lookbehind assertion, such as "\b".
1305 * A #GMatchInfo structure, used to get information on the match, is
1306 * stored in @match_info if not %NULL. Note that if @match_info is
1307 * not %NULL then it is created even if the function returns %FALSE,
1308 * i.e. you must free it regardless if regular expression actually
1311 * Returns: %TRUE is the string matched, %FALSE otherwise
1316 g_regex_match_all_full (const GRegex *regex,
1317 const gchar *string,
1319 gint start_position,
1320 GRegexMatchFlags match_options,
1321 GMatchInfo **match_info,
1327 g_return_val_if_fail (regex != NULL, FALSE);
1328 g_return_val_if_fail (string != NULL, FALSE);
1329 g_return_val_if_fail (start_position >= 0, FALSE);
1330 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1331 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1333 info = match_info_new (regex, string, string_len, start_position,
1334 match_options, TRUE);
1340 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1341 info->string, info->string_len,
1343 regex->match_opts | match_options,
1344 info->offsets, info->n_offsets,
1345 info->workspace, info->n_workspace);
1346 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1348 /* info->workspace is too small. */
1349 info->n_workspace *= 2;
1350 info->workspace = g_realloc (info->workspace,
1351 info->n_workspace * sizeof (gint));
1354 else if (info->matches == 0)
1356 /* info->offsets is too small. */
1357 info->n_offsets *= 2;
1358 info->offsets = g_realloc (info->offsets,
1359 info->n_offsets * sizeof (gint));
1362 else if (IS_PCRE_ERROR (info->matches))
1364 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1365 _("Error while matching regular expression %s: %s"),
1366 regex->pattern, match_error (info->matches));
1370 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1373 if (match_info != NULL)
1376 g_match_info_free (info);
1378 return info->matches >= 0;
1382 * g_regex_get_string_number:
1383 * @regex: #GRegex structure
1384 * @name: name of the subexpression
1386 * Retrieves the number of the subexpression named @name.
1388 * Returns: The number of the subexpression or -1 if @name
1394 g_regex_get_string_number (const GRegex *regex,
1399 g_return_val_if_fail (regex != NULL, -1);
1400 g_return_val_if_fail (name != NULL, -1);
1402 num = pcre_get_stringnumber (regex->pcre_re, name);
1403 if (num == PCRE_ERROR_NOSUBSTRING)
1410 * g_regex_split_simple:
1411 * @pattern: the regular expression
1412 * @string: the string to scan for matches
1413 * @compile_options: compile options for the regular expression
1414 * @match_options: match options
1416 * Breaks the string on the pattern, and returns an array of
1417 * the tokens. If the pattern contains capturing parentheses,
1418 * then the text for each of the substrings will also be returned.
1419 * If the pattern does not match anywhere in the string, then the
1420 * whole string is returned as the first token.
1422 * This function is equivalent to g_regex_split() but it does
1423 * not require to compile the pattern with g_regex_new(), avoiding
1424 * some lines of code when you need just to do a split without
1425 * extracting substrings, capture counts, and so on.
1427 * If this function is to be called on the same @pattern more than
1428 * once, it's more efficient to compile the pattern once with
1429 * g_regex_new() and then use g_regex_split().
1431 * As a special case, the result of splitting the empty string ""
1432 * is an empty vector, not a vector containing a single string.
1433 * The reason for this special case is that being able to represent
1434 * a empty vector is typically more useful than consistent handling
1435 * of empty elements. If you do need to represent empty elements,
1436 * you'll need to check for the empty string before calling this
1439 * A pattern that can match empty strings splits @string into
1440 * separate characters wherever it matches the empty string between
1441 * characters. For example splitting "ab c" using as a separator
1442 * "\s*", you will get "a", "b" and "c".
1444 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1449 g_regex_split_simple (const gchar *pattern,
1450 const gchar *string,
1451 GRegexCompileFlags compile_options,
1452 GRegexMatchFlags match_options)
1457 regex = g_regex_new (pattern, compile_options, 0, NULL);
1460 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1461 g_regex_unref (regex);
1467 * @regex: a #GRegex structure
1468 * @string: the string to split with the pattern
1469 * @match_options: match time option flags
1471 * Breaks the string on the pattern, and returns an array of the tokens.
1472 * If the pattern contains capturing parentheses, then the text for each
1473 * of the substrings will also be returned. If the pattern does not match
1474 * anywhere in the string, then the whole string is returned as the first
1477 * As a special case, the result of splitting the empty string "" is an
1478 * empty vector, not a vector containing a single string. The reason for
1479 * this special case is that being able to represent a empty vector is
1480 * typically more useful than consistent handling of empty elements. If
1481 * you do need to represent empty elements, you'll need to check for the
1482 * empty string before calling this function.
1484 * A pattern that can match empty strings splits @string into separate
1485 * characters wherever it matches the empty string between characters.
1486 * For example splitting "ab c" using as a separator "\s*", you will get
1489 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1494 g_regex_split (const GRegex *regex,
1495 const gchar *string,
1496 GRegexMatchFlags match_options)
1498 return g_regex_split_full (regex, string, -1, 0,
1499 match_options, 0, NULL);
1503 * g_regex_split_full:
1504 * @regex: a #GRegex structure
1505 * @string: the string to split with the pattern
1506 * @string_len: the length of @string, or -1 if @string is nul-terminated
1507 * @start_position: starting index of the string to match
1508 * @match_options: match time option flags
1509 * @max_tokens: the maximum number of tokens to split @string into.
1510 * If this is less than 1, the string is split completely
1511 * @error: return location for a #GError
1513 * Breaks the string on the pattern, and returns an array of the tokens.
1514 * If the pattern contains capturing parentheses, then the text for each
1515 * of the substrings will also be returned. If the pattern does not match
1516 * anywhere in the string, then the whole string is returned as the first
1519 * As a special case, the result of splitting the empty string "" is an
1520 * empty vector, not a vector containing a single string. The reason for
1521 * this special case is that being able to represent a empty vector is
1522 * typically more useful than consistent handling of empty elements. If
1523 * you do need to represent empty elements, you'll need to check for the
1524 * empty string before calling this function.
1526 * A pattern that can match empty strings splits @string into separate
1527 * characters wherever it matches the empty string between characters.
1528 * For example splitting "ab c" using as a separator "\s*", you will get
1531 * Setting @start_position differs from just passing over a shortened
1532 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1533 * that begins with any kind of lookbehind assertion, such as "\b".
1535 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1540 g_regex_split_full (const GRegex *regex,
1541 const gchar *string,
1543 gint start_position,
1544 GRegexMatchFlags match_options,
1548 GError *tmp_error = NULL;
1549 GMatchInfo *match_info;
1554 /* position of the last separator. */
1555 gint last_separator_end;
1556 /* was the last match 0 bytes long? */
1557 gboolean last_match_is_empty;
1558 /* the returned array of char **s */
1559 gchar **string_list;
1561 g_return_val_if_fail (regex != NULL, NULL);
1562 g_return_val_if_fail (string != NULL, NULL);
1563 g_return_val_if_fail (start_position >= 0, NULL);
1564 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1565 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1567 if (max_tokens <= 0)
1568 max_tokens = G_MAXINT;
1571 string_len = strlen (string);
1573 /* zero-length string */
1574 if (string_len - start_position == 0)
1575 return g_new0 (gchar *, 1);
1577 if (max_tokens == 1)
1579 string_list = g_new0 (gchar *, 2);
1580 string_list[0] = g_strndup (&string[start_position],
1581 string_len - start_position);
1587 last_separator_end = start_position;
1588 last_match_is_empty = FALSE;
1590 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1591 match_options, &match_info, &tmp_error);
1592 while (tmp_error == NULL)
1596 last_match_is_empty =
1597 (match_info->offsets[0] == match_info->offsets[1]);
1599 /* we need to skip empty separators at the same position of the end
1600 * of another separator. e.g. the string is "a b" and the separator
1601 * is " *", so from 1 to 2 we have a match and at position 2 we have
1602 * an empty match. */
1603 if (last_separator_end != match_info->offsets[1])
1608 token = g_strndup (string + last_separator_end,
1609 match_info->offsets[0] - last_separator_end);
1610 list = g_list_prepend (list, token);
1613 /* if there were substrings, these need to be added to
1615 match_count = g_match_info_get_match_count (match_info);
1616 if (match_count > 1)
1618 for (i = 1; i < match_count; i++)
1619 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1625 /* if there was no match, copy to end of string. */
1626 if (!last_match_is_empty)
1628 gchar *token = g_strndup (string + last_separator_end,
1629 match_info->string_len - last_separator_end);
1630 list = g_list_prepend (list, token);
1632 /* no more tokens, end the loop. */
1636 /* -1 to leave room for the last part. */
1637 if (token_count >= max_tokens - 1)
1639 /* we have reached the maximum number of tokens, so we copy
1640 * the remaining part of the string. */
1641 if (last_match_is_empty)
1643 /* the last match was empty, so we have moved one char
1644 * after the real position to avoid empty matches at the
1646 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1648 /* the if is needed in the case we have terminated the available
1649 * tokens, but we are at the end of the string, so there are no
1650 * characters left to copy. */
1651 if (string_len > match_info->pos)
1653 gchar *token = g_strndup (string + match_info->pos,
1654 string_len - match_info->pos);
1655 list = g_list_prepend (list, token);
1661 last_separator_end = match_info->pos;
1662 if (last_match_is_empty)
1663 /* if the last match was empty, g_match_info_next() has moved
1664 * forward to avoid infinite loops, but we still need to copy that
1666 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1668 match_ok = g_match_info_next (match_info, &tmp_error);
1670 g_match_info_free (match_info);
1671 if (tmp_error != NULL)
1673 g_propagate_error (error, tmp_error);
1674 g_list_foreach (list, (GFunc)g_free, NULL);
1676 match_info->pos = -1;
1680 string_list = g_new (gchar *, g_list_length (list) + 1);
1682 for (last = g_list_last (list); last; last = g_list_previous (last))
1683 string_list[i++] = last->data;
1684 string_list[i] = NULL;
1693 REPL_TYPE_CHARACTER,
1694 REPL_TYPE_SYMBOLIC_REFERENCE,
1695 REPL_TYPE_NUMERIC_REFERENCE,
1696 REPL_TYPE_CHANGE_CASE
1701 CHANGE_CASE_NONE = 1 << 0,
1702 CHANGE_CASE_UPPER = 1 << 1,
1703 CHANGE_CASE_LOWER = 1 << 2,
1704 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1705 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1706 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1707 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1708 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1711 struct _InterpolationData
1717 ChangeCase change_case;
1721 free_interpolation_data (InterpolationData *data)
1723 g_free (data->text);
1727 static const gchar *
1728 expand_escape (const gchar *replacement,
1730 InterpolationData *data,
1735 const gchar *error_detail;
1737 GError *tmp_error = NULL;
1745 data->type = REPL_TYPE_CHARACTER;
1750 data->type = REPL_TYPE_CHARACTER;
1755 data->type = REPL_TYPE_CHARACTER;
1760 data->type = REPL_TYPE_CHARACTER;
1765 data->type = REPL_TYPE_CHARACTER;
1770 data->type = REPL_TYPE_CHARACTER;
1775 data->type = REPL_TYPE_CHARACTER;
1780 data->type = REPL_TYPE_CHARACTER;
1790 h = g_ascii_xdigit_value (*p);
1793 error_detail = _("hexadecimal digit or '}' expected");
1804 for (i = 0; i < 2; i++)
1806 h = g_ascii_xdigit_value (*p);
1809 error_detail = _("hexadecimal digit expected");
1816 data->type = REPL_TYPE_STRING;
1817 data->text = g_new0 (gchar, 8);
1818 g_unichar_to_utf8 (x, data->text);
1822 data->type = REPL_TYPE_CHANGE_CASE;
1823 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1827 data->type = REPL_TYPE_CHANGE_CASE;
1828 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1832 data->type = REPL_TYPE_CHANGE_CASE;
1833 data->change_case = CHANGE_CASE_LOWER;
1837 data->type = REPL_TYPE_CHANGE_CASE;
1838 data->change_case = CHANGE_CASE_UPPER;
1842 data->type = REPL_TYPE_CHANGE_CASE;
1843 data->change_case = CHANGE_CASE_NONE;
1849 error_detail = _("missing '<' in symbolic reference");
1858 error_detail = _("unfinished symbolic reference");
1865 error_detail = _("zero-length symbolic reference");
1868 if (g_ascii_isdigit (*q))
1873 h = g_ascii_digit_value (*q);
1876 error_detail = _("digit expected");
1885 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1892 if (!g_ascii_isalnum (*r))
1894 error_detail = _("illegal symbolic reference");
1901 data->text = g_strndup (q, p - q);
1902 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1907 /* if \0 is followed by a number is an octal number representing a
1908 * character, else it is a numeric reference. */
1909 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1912 p = g_utf8_next_char (p);
1925 for (i = 0; i < 3; i++)
1927 h = g_ascii_digit_value (*p);
1937 if (i == 2 && base == 10)
1943 if (base == 8 || i == 3)
1945 data->type = REPL_TYPE_STRING;
1946 data->text = g_new0 (gchar, 8);
1947 g_unichar_to_utf8 (x, data->text);
1951 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1956 error_detail = _("stray final '\\'");
1960 error_detail = _("unknown escape sequence");
1967 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1968 tmp_error = g_error_new (G_REGEX_ERROR,
1969 G_REGEX_ERROR_REPLACE,
1970 _("Error while parsing replacement "
1971 "text \"%s\" at char %lu: %s"),
1973 (gulong)(p - replacement),
1975 g_propagate_error (error, tmp_error);
1981 split_replacement (const gchar *replacement,
1985 InterpolationData *data;
1986 const gchar *p, *start;
1988 start = p = replacement;
1993 data = g_new0 (InterpolationData, 1);
1994 start = p = expand_escape (replacement, p, data, error);
1997 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1999 free_interpolation_data (data);
2003 list = g_list_prepend (list, data);
2008 if (*p == '\\' || *p == '\0')
2012 data = g_new0 (InterpolationData, 1);
2013 data->text = g_strndup (start, p - start);
2014 data->type = REPL_TYPE_STRING;
2015 list = g_list_prepend (list, data);
2021 return g_list_reverse (list);
2024 /* Change the case of c based on change_case. */
2025 #define CHANGE_CASE(c, change_case) \
2026 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2027 g_unichar_tolower (c) : \
2028 g_unichar_toupper (c))
2031 string_append (GString *string,
2033 ChangeCase *change_case)
2037 if (text[0] == '\0')
2040 if (*change_case == CHANGE_CASE_NONE)
2042 g_string_append (string, text);
2044 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2046 c = g_utf8_get_char (text);
2047 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2048 g_string_append (string, g_utf8_next_char (text));
2049 *change_case = CHANGE_CASE_NONE;
2053 while (*text != '\0')
2055 c = g_utf8_get_char (text);
2056 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2057 text = g_utf8_next_char (text);
2063 interpolate_replacement (const GMatchInfo *match_info,
2068 InterpolationData *idata;
2070 ChangeCase change_case = CHANGE_CASE_NONE;
2072 for (list = data; list; list = list->next)
2075 switch (idata->type)
2077 case REPL_TYPE_STRING:
2078 string_append (result, idata->text, &change_case);
2080 case REPL_TYPE_CHARACTER:
2081 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2082 if (change_case & CHANGE_CASE_SINGLE_MASK)
2083 change_case = CHANGE_CASE_NONE;
2085 case REPL_TYPE_NUMERIC_REFERENCE:
2086 match = g_match_info_fetch (match_info, idata->num);
2089 string_append (result, match, &change_case);
2093 case REPL_TYPE_SYMBOLIC_REFERENCE:
2094 match = g_match_info_fetch_named (match_info, idata->text);
2097 string_append (result, match, &change_case);
2101 case REPL_TYPE_CHANGE_CASE:
2102 change_case = idata->change_case;
2110 /* whether actual match_info is needed for replacement, i.e.
2111 * whether there are references
2114 interpolation_list_needs_match (GList *list)
2116 while (list != NULL)
2118 InterpolationData *data = list->data;
2120 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2121 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2134 * @regex: a #GRegex structure
2135 * @string: the string to perform matches against
2136 * @string_len: the length of @string, or -1 if @string is nul-terminated
2137 * @start_position: starting index of the string to match
2138 * @replacement: text to replace each match with
2139 * @match_options: options for the match
2140 * @error: location to store the error occuring, or %NULL to ignore errors
2142 * Replaces all occurances of the pattern in @regex with the
2143 * replacement text. Backreferences of the form '\number' or
2144 * '\g<number>' in the replacement text are interpolated by the
2145 * number-th captured subexpression of the match, '\g<name>' refers
2146 * to the captured subexpression with the given name. '\0' refers to the
2147 * complete match, but '\0' followed by a number is the octal representation
2148 * of a character. To include a literal '\' in the replacement, write '\\'.
2149 * There are also escapes that changes the case of the following text:
2152 * <varlistentry><term>\l</term>
2154 * <para>Convert to lower case the next character</para>
2157 * <varlistentry><term>\u</term>
2159 * <para>Convert to upper case the next character</para>
2162 * <varlistentry><term>\L</term>
2164 * <para>Convert to lower case till \E</para>
2167 * <varlistentry><term>\U</term>
2169 * <para>Convert to upper case till \E</para>
2172 * <varlistentry><term>\E</term>
2174 * <para>End case modification</para>
2179 * If you do not need to use backreferences use g_regex_replace_literal().
2181 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2182 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2183 * you can use g_regex_replace_literal().
2185 * Setting @start_position differs from just passing over a shortened
2186 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2187 * begins with any kind of lookbehind assertion, such as "\b".
2189 * Returns: a newly allocated string containing the replacements
2194 g_regex_replace (const GRegex *regex,
2195 const gchar *string,
2197 gint start_position,
2198 const gchar *replacement,
2199 GRegexMatchFlags match_options,
2204 GError *tmp_error = NULL;
2206 g_return_val_if_fail (regex != NULL, NULL);
2207 g_return_val_if_fail (string != NULL, NULL);
2208 g_return_val_if_fail (start_position >= 0, NULL);
2209 g_return_val_if_fail (replacement != NULL, NULL);
2210 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2211 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2213 list = split_replacement (replacement, &tmp_error);
2214 if (tmp_error != NULL)
2216 g_propagate_error (error, tmp_error);
2220 result = g_regex_replace_eval (regex,
2221 string, string_len, start_position,
2223 interpolate_replacement,
2226 if (tmp_error != NULL)
2227 g_propagate_error (error, tmp_error);
2229 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2236 literal_replacement (const GMatchInfo *match_info,
2240 g_string_append (result, data);
2245 * g_regex_replace_literal:
2246 * @regex: a #GRegex structure
2247 * @string: the string to perform matches against
2248 * @string_len: the length of @string, or -1 if @string is nul-terminated
2249 * @start_position: starting index of the string to match
2250 * @replacement: text to replace each match with
2251 * @match_options: options for the match
2252 * @error: location to store the error occuring, or %NULL to ignore errors
2254 * Replaces all occurances of the pattern in @regex with the
2255 * replacement text. @replacement is replaced literally, to
2256 * include backreferences use g_regex_replace().
2258 * Setting @start_position differs from just passing over a
2259 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2260 * case of a pattern that begins with any kind of lookbehind
2261 * assertion, such as "\b".
2263 * Returns: a newly allocated string containing the replacements
2268 g_regex_replace_literal (const GRegex *regex,
2269 const gchar *string,
2271 gint start_position,
2272 const gchar *replacement,
2273 GRegexMatchFlags match_options,
2276 g_return_val_if_fail (replacement != NULL, NULL);
2277 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2279 return g_regex_replace_eval (regex,
2280 string, string_len, start_position,
2282 literal_replacement,
2283 (gpointer)replacement,
2288 * g_regex_replace_eval:
2289 * @regex: a #GRegex structure from g_regex_new()
2290 * @string: string to perform matches against
2291 * @string_len: the length of @string, or -1 if @string is nul-terminated
2292 * @start_position: starting index of the string to match
2293 * @match_options: options for the match
2294 * @eval: a function to call for each match
2295 * @user_data: user data to pass to the function
2296 * @error: location to store the error occuring, or %NULL to ignore errors
2298 * Replaces occurances of the pattern in regex with the output of
2299 * @eval for that occurance.
2301 * Setting @start_position differs from just passing over a shortened
2302 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2303 * that begins with any kind of lookbehind assertion, such as "\b".
2305 * Returns: a newly allocated string containing the replacements
2310 g_regex_replace_eval (const GRegex *regex,
2311 const gchar *string,
2313 gint start_position,
2314 GRegexMatchFlags match_options,
2315 GRegexEvalCallback eval,
2319 GMatchInfo *match_info;
2322 gboolean done = FALSE;
2323 GError *tmp_error = NULL;
2325 g_return_val_if_fail (regex != NULL, NULL);
2326 g_return_val_if_fail (string != NULL, NULL);
2327 g_return_val_if_fail (start_position >= 0, NULL);
2328 g_return_val_if_fail (eval != NULL, NULL);
2329 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2332 string_len = strlen (string);
2334 result = g_string_sized_new (string_len);
2336 /* run down the string making matches. */
2337 g_regex_match_full (regex, string, string_len, start_position,
2338 match_options, &match_info, &tmp_error);
2339 while (!done && g_match_info_matches (match_info))
2341 g_string_append_len (result,
2343 match_info->offsets[0] - str_pos);
2344 done = (*eval) (match_info, result, user_data);
2345 str_pos = match_info->offsets[1];
2346 g_match_info_next (match_info, &tmp_error);
2348 g_match_info_free (match_info);
2349 if (tmp_error != NULL)
2351 g_propagate_error (error, tmp_error);
2352 g_string_free (result, TRUE);
2356 g_string_append_len (result, string + str_pos, string_len - str_pos);
2357 return g_string_free (result, FALSE);
2361 * g_regex_check_replacement:
2362 * @replacement: the replacement string
2363 * @has_references: location to store information about
2364 * references in @replacement or %NULL
2365 * @error: location to store error
2367 * Checks whether @replacement is a valid replacement string
2368 * (see g_regex_replace()), i.e. that all escape sequences in
2371 * If @has_references is not %NULL then @replacement is checked
2372 * for pattern references. For instance, replacement text 'foo\n'
2373 * does not contain references and may be evaluated without information
2374 * about actual match, but '\0\1' (whole match followed by first
2375 * subpattern) requires valid #GMatchInfo object.
2377 * Returns: whether @replacement is a valid replacement string
2382 g_regex_check_replacement (const gchar *replacement,
2383 gboolean *has_references,
2389 list = split_replacement (replacement, &tmp);
2393 g_propagate_error (error, tmp);
2398 *has_references = interpolation_list_needs_match (list);
2400 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2407 * g_regex_escape_string:
2408 * @string: the string to escape
2409 * @length: the length of @string, or -1 if @string is nul-terminated
2411 * Escapes the special characters used for regular expressions
2412 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
2413 * function is useful to dynamically generate regular expressions.
2415 * @string can contain nul characters that are replaced with "\0",
2416 * in this case remember to specify the correct length of @string
2419 * Returns: a newly-allocated escaped string
2424 g_regex_escape_string (const gchar *string,
2428 const char *p, *piece_start, *end;
2430 g_return_val_if_fail (string != NULL, NULL);
2433 length = strlen (string);
2435 end = string + length;
2436 p = piece_start = string;
2437 escaped = g_string_sized_new (length + 1);
2458 if (p != piece_start)
2459 /* copy the previous piece. */
2460 g_string_append_len (escaped, piece_start, p - piece_start);
2461 g_string_append_c (escaped, '\\');
2463 g_string_append_c (escaped, '0');
2465 g_string_append_c (escaped, *p);
2469 p = g_utf8_next_char (p);
2474 if (piece_start < end)
2475 g_string_append_len (escaped, piece_start, end - piece_start);
2477 return g_string_free (escaped, FALSE);
2480 #define __G_REGEX_C__
2481 #include "galiasdef.c"