1 /* GRegex -- regular expression API wrapper around PCRE.
3 * Copyright (C) 1999, 2000 Scott Wimer
4 * Copyright (C) 2004, Matthias Clasen <mclasen@redhat.com>
5 * Copyright (C) 2005 - 2007, Marco Barisione <marco@barisione.org>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27 #include <glib/gi18n.h>
30 #ifdef USE_SYSTEM_PCRE
33 #include "pcre/pcre.h"
38 /* Mask of all the possible values for GRegexCompileFlags. */
39 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
44 G_REGEX_DOLLAR_ENDONLY | \
47 G_REGEX_NO_AUTO_CAPTURE | \
50 G_REGEX_NEWLINE_CR | \
51 G_REGEX_NEWLINE_LF | \
54 /* Mask of all the possible values for GRegexMatchFlags. */
55 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
56 G_REGEX_MATCH_NOTBOL | \
57 G_REGEX_MATCH_NOTEOL | \
58 G_REGEX_MATCH_NOTEMPTY | \
59 G_REGEX_MATCH_PARTIAL | \
60 G_REGEX_MATCH_NEWLINE_CR | \
61 G_REGEX_MATCH_NEWLINE_LF | \
62 G_REGEX_MATCH_NEWLINE_CRLF | \
63 G_REGEX_MATCH_NEWLINE_ANY)
65 /* if the string is in UTF-8 use g_utf8_ functions, else use
67 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
68 g_utf8_next_char (s) : \
70 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
71 g_utf8_prev_char (s) : \
76 GRegex *regex; /* the regex */
77 GRegexMatchFlags match_opts; /* options used at match time on the regex */
78 gint matches; /* number of matching sub patterns */
79 gint pos; /* position in the string where last match left off */
80 gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
81 gint n_offsets; /* number of offsets */
82 gint *workspace; /* workspace for pcre_dfa_exec() */
83 gint n_workspace; /* number of workspace elements */
84 const gchar *string; /* string passed to the match function */
85 gssize string_len; /* length of string */
90 volatile guint ref_count; /* the ref count for the immutable part */
91 gchar *pattern; /* the pattern */
92 pcre *pcre_re; /* compiled form of the pattern */
93 GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
94 GRegexMatchFlags match_opts; /* options used at match time on the regex */
95 pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
98 /* TRUE if ret is an error code, FALSE otherwise. */
99 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
101 typedef struct _InterpolationData InterpolationData;
102 static gboolean interpolation_list_needs_match (GList *list);
103 static gboolean interpolate_replacement (const GMatchInfo *match_info,
106 static GList *split_replacement (const gchar *replacement,
108 static void free_interpolation_data (InterpolationData *data);
112 match_error (gint errcode)
116 case PCRE_ERROR_NOMATCH:
119 case PCRE_ERROR_NULL:
120 /* NULL argument, this should not happen in GRegex */
121 g_warning ("A NULL argument was passed to PCRE");
123 case PCRE_ERROR_BADOPTION:
124 return "bad options";
125 case PCRE_ERROR_BADMAGIC:
126 return _("corrupted object");
127 case PCRE_ERROR_UNKNOWN_OPCODE:
128 return N_("internal error or corrupted object");
129 case PCRE_ERROR_NOMEMORY:
130 return _("out of memory");
131 case PCRE_ERROR_NOSUBSTRING:
132 /* not used by pcre_exec() */
134 case PCRE_ERROR_MATCHLIMIT:
135 return _("backtracking limit reached");
136 case PCRE_ERROR_CALLOUT:
137 /* callouts are not implemented */
139 case PCRE_ERROR_BADUTF8:
140 case PCRE_ERROR_BADUTF8_OFFSET:
141 /* we do not check if strings are valid */
143 case PCRE_ERROR_PARTIAL:
146 case PCRE_ERROR_BADPARTIAL:
147 return _("the pattern contains items not supported for partial matching");
148 case PCRE_ERROR_INTERNAL:
149 return _("internal error");
150 case PCRE_ERROR_BADCOUNT:
151 /* negative ovecsize, this should not happen in GRegex */
152 g_warning ("A negative ovecsize was passed to PCRE");
154 case PCRE_ERROR_DFA_UITEM:
155 return _("the pattern contains items not supported for partial matching");
156 case PCRE_ERROR_DFA_UCOND:
157 return _("back references as conditions are not supported for partial matching");
158 case PCRE_ERROR_DFA_UMLIMIT:
159 /* the match_field field is not used in GRegex */
161 case PCRE_ERROR_DFA_WSSIZE:
162 /* handled expanding the workspace */
164 case PCRE_ERROR_DFA_RECURSE:
165 case PCRE_ERROR_RECURSIONLIMIT:
166 return _("recursion limit reached");
167 case PCRE_ERROR_NULLWSLIMIT:
168 return _("workspace limit for empty substrings reached");
169 case PCRE_ERROR_BADNEWLINE:
170 return _("invalid combination of newline flags");
174 return _("unknown error");
181 match_info_new (const GRegex *regex,
188 GMatchInfo *match_info;
191 string_len = strlen (string);
193 match_info = g_new0 (GMatchInfo, 1);
194 match_info->regex = g_regex_ref ((GRegex *)regex);
195 match_info->string = string;
196 match_info->string_len = string_len;
197 match_info->matches = PCRE_ERROR_NOMATCH;
198 match_info->pos = start_position;
199 match_info->match_opts = match_options;
203 /* These values should be enough for most cases, if they are not
204 * enough g_regex_match_all_full() will expand them. */
205 match_info->n_offsets = 24;
206 match_info->n_workspace = 100;
207 match_info->workspace = g_new (gint, match_info->n_workspace);
212 pcre_fullinfo (regex->pcre_re, regex->extra,
213 PCRE_INFO_CAPTURECOUNT, &capture_count);
214 match_info->n_offsets = (capture_count + 1) * 3;
216 match_info->offsets = g_new0 (gint, match_info->n_offsets);
222 * g_match_info_get_regex:
223 * @match_info: a #GMatchInfo
225 * Returns #GRegex object used in @match_info. It belongs to glib
226 * and must not be freed. Use g_regex_ref() if you need to keep it
227 * after you free @match_info object.
229 * Returns: #GRegex object used in @match_info
234 g_match_info_get_regex (const GMatchInfo *match_info)
236 g_return_val_if_fail (match_info != NULL, NULL);
237 return match_info->regex;
241 * g_match_info_get_string:
242 * @match_info: a #GMatchInfo
244 * Returns the string searched with @match_info. This is the
245 * string passed to g_regex_match() or g_regex_replace() so
246 * you may not free it before calling this function.
248 * Returns: the string searched with @match_info
253 g_match_info_get_string (const GMatchInfo *match_info)
255 g_return_val_if_fail (match_info != NULL, NULL);
256 return match_info->string;
261 * @match_info: a #GMatchInfo
263 * Frees all the memory associated with the #GMatchInfo structure.
268 g_match_info_free (GMatchInfo *match_info)
272 g_regex_unref (match_info->regex);
273 g_free (match_info->offsets);
274 g_free (match_info->workspace);
281 * @match_info: a #GMatchInfo structure
282 * @error: location to store the error occuring, or NULL to ignore errors
284 * Scans for the next match using the same parameters of the previous
285 * call to g_regex_match_full() or g_regex_match() that returned
288 * The match is done on the string passed to the match function, so you
289 * cannot free it before calling this function.
291 * Returns: %TRUE is the string matched, %FALSE otherwise
296 g_match_info_next (GMatchInfo *match_info,
299 g_return_val_if_fail (match_info != NULL, FALSE);
300 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
301 g_return_val_if_fail (match_info->pos >= 0, FALSE);
303 match_info->matches = pcre_exec (match_info->regex->pcre_re,
304 match_info->regex->extra,
306 match_info->string_len,
308 match_info->regex->match_opts |
309 match_info->match_opts,
311 match_info->n_offsets);
312 if (IS_PCRE_ERROR (match_info->matches))
314 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
315 _("Error while matching regular expression %s: %s"),
316 match_info->regex->pattern, match_error (match_info->matches));
320 /* avoid infinite loops if the pattern is an empty string or something
322 if (match_info->pos == match_info->offsets[1])
324 if (match_info->pos > match_info->string_len)
326 /* we have reached the end of the string */
327 match_info->pos = -1;
328 match_info->matches = PCRE_ERROR_NOMATCH;
331 match_info->pos = NEXT_CHAR (match_info->regex,
332 &match_info->string[match_info->pos]) -
337 match_info->pos = match_info->offsets[1];
340 return match_info->matches >= 0;
344 * g_match_info_matches:
345 * @match_info: a #GMatchInfo structure
347 * Returns: %TRUE if the previous match operation succeeded, %FALSE
353 g_match_info_matches (const GMatchInfo *match_info)
355 g_return_val_if_fail (match_info != NULL, FALSE);
357 return match_info->matches >= 0;
361 * g_match_info_get_match_count:
362 * @match_info: a #GMatchInfo structure
364 * Retrieves the number of matched substrings (including substring 0, that
365 * is the whole matched text), so 1 is returned if the pattern has no
366 * substrings in it and 0 is returned if the match failed.
368 * If the last match was obtained using the DFA algorithm, that is using
369 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
370 * count is not that of the number of capturing parentheses but that of
371 * the number of matched substrings.
373 * Returns: Number of matched substrings, or -1 if an error occurred
378 g_match_info_get_match_count (const GMatchInfo *match_info)
380 g_return_val_if_fail (match_info, -1);
382 if (match_info->matches == PCRE_ERROR_NOMATCH)
385 else if (match_info->matches < PCRE_ERROR_NOMATCH)
390 return match_info->matches;
394 * g_match_info_is_partial_match:
395 * @match_info: a #GMatchInfo structure
397 * Usually if the string passed to g_regex_match*() matches as far as
398 * it goes, but is too short to match the entire pattern, %FALSE is
399 * returned. There are circumstances where it might be helpful to
400 * distinguish this case from other cases in which there is no match.
402 * Consider, for example, an application where a human is required to
403 * type in data for a field with specific formatting requirements. An
404 * example might be a date in the form ddmmmyy, defined by the pattern
405 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
406 * If the application sees the user’s keystrokes one by one, and can
407 * check that what has been typed so far is potentially valid, it is
408 * able to raise an error as soon as a mistake is made.
410 * GRegex supports the concept of partial matching by means of the
411 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
412 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
413 * for a complete match, %FALSE otherwise. But, when this functions
414 * returns %FALSE, you can check if the match was partial calling
415 * g_match_info_is_partial_match().
417 * When using partial matching you cannot use g_match_info_fetch*().
419 * Because of the way certain internal optimizations are implemented the
420 * partial matching algorithm cannot be used with all patterns. So repeated
421 * single characters such as "a{2,4}" and repeated single metasequences such
422 * as "\d+" are not permitted if the maximum number of occurrences is
423 * greater than one. Optional items such as "\d?" (where the maximum is one)
424 * are permitted. Quantifiers with any values are permitted after
425 * parentheses, so the invalid examples above can be coded thus "(a){2,4}"
426 * and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set for a pattern that does
427 * not conform to the restrictions, matching functions return an error.
429 * Returns: %TRUE if the match was partial, %FALSE otherwise
434 g_match_info_is_partial_match (const GMatchInfo *match_info)
436 g_return_val_if_fail (match_info != NULL, FALSE);
438 return match_info->matches == PCRE_ERROR_PARTIAL;
442 * g_match_info_expand_references:
443 * @match_info: a #GMatchInfo or %NULL
444 * @string_to_expand: the string to expand
445 * @error: location to store the error occuring, or %NULL to ignore errors
447 * Returns a new string containing the text in @string_to_expand with
448 * references and escape sequences expanded. References refer to the last
449 * match done with @string against @regex and have the same syntax used by
452 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
453 * passed to g_regex_new().
455 * The backreferences are extracted from the string passed to the match
456 * function, so you cannot call this function after freeing the string.
458 * @match_info may be %NULL in which case @string_to_expand must not
459 * contain references. For instance "foo\n" does not refer to an actual
460 * pattern and '\n' merely will be replaced with \n character,
461 * while to expand "\0" (whole match) one needs the result of a match.
462 * Use g_regex_check_replacement() to find out whether @string_to_expand
463 * contains references.
465 * Returns: the expanded string, or %NULL if an error occurred
470 g_match_info_expand_references (const GMatchInfo *match_info,
471 const gchar *string_to_expand,
476 GError *tmp_error = NULL;
478 g_return_val_if_fail (string_to_expand != NULL, NULL);
479 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
481 list = split_replacement (string_to_expand, &tmp_error);
482 if (tmp_error != NULL)
484 g_propagate_error (error, tmp_error);
488 if (!match_info && interpolation_list_needs_match (list))
490 g_critical ("String '%s' contains references to the match, can't "
491 "expand references without GMatchInfo object",
496 result = g_string_sized_new (strlen (string_to_expand));
497 interpolate_replacement (match_info, result, list);
499 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
502 return g_string_free (result, FALSE);
506 * g_match_info_fetch:
507 * @match_info: #GMatchInfo structure
508 * @match_num: number of the sub expression
510 * Retrieves the text matching the @match_num<!-- -->'th capturing parentheses.
511 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
514 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
515 * sub pattern 1, matching "b" against "(a)?b") then an empty string is
518 * If the match was obtained using the DFA algorithm, that is using
519 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
520 * string is not that of a set of parentheses but that of a matched
521 * substring. Substrings are matched in reverse order of length, so 0 is
524 * The string is fetched from the string passed to the match function,
525 * so you cannot call this function after freeing the string.
527 * Returns: The matched substring, or %NULL if an error occurred.
528 * You have to free the string yourself
533 g_match_info_fetch (const GMatchInfo *match_info,
536 /* we cannot use pcre_get_substring() because it allocates the
537 * string using pcre_malloc(). */
541 g_return_val_if_fail (match_info != NULL, NULL);
542 g_return_val_if_fail (match_num >= 0, NULL);
544 /* match_num does not exist or it didn't matched, i.e. matching "b"
545 * against "(a)?b" then group 0 is empty. */
546 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
548 else if (start == -1)
549 match = g_strdup ("");
551 match = g_strndup (&match_info->string[start], end - start);
557 * g_match_info_fetch_pos:
558 * @match_info: #GMatchInfo structure
559 * @match_num: number of the sub expression
560 * @start_pos: pointer to location where to store the start position
561 * @end_pos: pointer to location where to store the end position
563 * Retrieves the position of the @match_num<!-- -->'th capturing parentheses.
564 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
567 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
568 * sub pattern 1, matching "b" against "(a)?b") then @start_pos and @end_pos
569 * are set to -1 and %TRUE is returned.
571 * If the match was obtained using the DFA algorithm, that is using
572 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
573 * position is not that of a set of parentheses but that of a matched
574 * substring. Substrings are matched in reverse order of length, so 0 is
577 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
578 * position cannot be fetched, @start_pos and @end_pos are left
584 g_match_info_fetch_pos (const GMatchInfo *match_info,
589 g_return_val_if_fail (match_info != NULL, FALSE);
590 g_return_val_if_fail (match_num >= 0, FALSE);
592 /* make sure the sub expression number they're requesting is less than
593 * the total number of sub expressions that were matched. */
594 if (match_num >= match_info->matches)
597 if (start_pos != NULL)
598 *start_pos = match_info->offsets[2 * match_num];
601 *end_pos = match_info->offsets[2 * match_num + 1];
607 * Returns number of first matched subpattern with name @name.
608 * There may be more than one in case when DUPNAMES is used,
609 * and not all subpatterns with that name match;
610 * pcre_get_stringnumber() does not work in that case.
613 get_matched_substring_number (const GMatchInfo *match_info,
620 if ((match_info->regex->compile_opts & G_REGEX_DUPNAMES) == 0)
621 return pcre_get_stringnumber (match_info->regex->pcre_re, name);
623 /* This code is copied from pcre_get.c: get_first_set() */
624 entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re,
632 for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
634 gint n = (entry[0] << 8) + entry[1];
635 if (match_info->offsets[n*2] >= 0)
639 return (first[0] << 8) + first[1];
643 * g_match_info_fetch_named:
644 * @match_info: #GMatchInfo structure
645 * @name: name of the subexpression
647 * Retrieves the text matching the capturing parentheses named @name.
649 * If @name is a valid sub pattern name but it didn't match anything (e.g.
650 * sub pattern "X", matching "b" against "(?P<X>a)?b") then an empty
651 * string is returned.
653 * The string is fetched from the string passed to the match function,
654 * so you cannot call this function after freeing the string.
656 * Returns: The matched substring, or %NULL if an error occurred.
657 * You have to free the string yourself
662 g_match_info_fetch_named (const GMatchInfo *match_info,
665 /* we cannot use pcre_get_named_substring() because it allocates the
666 * string using pcre_malloc(). */
669 g_return_val_if_fail (match_info != NULL, NULL);
670 g_return_val_if_fail (name != NULL, NULL);
672 num = get_matched_substring_number (match_info, name);
676 return g_match_info_fetch (match_info, num);
680 * g_match_info_fetch_named_pos:
681 * @match_info: #GMatchInfo structure
682 * @name: name of the subexpression
683 * @start_pos: pointer to location where to store the start position
684 * @end_pos: pointer to location where to store the end position
686 * Retrieves the position of the capturing parentheses named @name.
688 * If @name is a valid sub pattern name but it didn't match anything (e.g.
689 * sub pattern "X", matching "b" against "(?P<X>a)?b") then @start_pos and
690 * @end_pos are set to -1 and %TRUE is returned.
692 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
693 * position cannot be fetched, @start_pos and @end_pos are left
699 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
706 g_return_val_if_fail (match_info != NULL, FALSE);
707 g_return_val_if_fail (name != NULL, FALSE);
709 num = get_matched_substring_number (match_info, name);
713 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
717 * g_match_info_fetch_all:
718 * @match_info: a #GMatchInfo structure
720 * Bundles up pointers to each of the matching substrings from a match
721 * and stores them in an array of gchar pointers. The first element in
722 * the returned array is the match number 0, i.e. the entire matched
725 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
726 * "b" against "(a)?b") then an empty string is inserted.
728 * If the last match was obtained using the DFA algorithm, that is using
729 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
730 * strings are not that matched by sets of parentheses but that of the
731 * matched substring. Substrings are matched in reverse order of length,
732 * so the first one is the longest match.
734 * The strings are fetched from the string passed to the match function,
735 * so you cannot call this function after freeing the string.
737 * Returns: a %NULL-terminated array of gchar * pointers. It must be freed
738 * using g_strfreev(). If the previous match failed %NULL is
744 g_match_info_fetch_all (const GMatchInfo *match_info)
746 /* we cannot use pcre_get_substring_list() because the returned value
747 * isn't suitable for g_strfreev(). */
751 g_return_val_if_fail (match_info != NULL, FALSE);
753 if (match_info->matches < 0)
756 result = g_new (gchar *, match_info->matches + 1);
757 for (i = 0; i < match_info->matches; i++)
758 result[i] = g_match_info_fetch (match_info, i);
768 g_regex_error_quark (void)
770 static GQuark error_quark = 0;
772 if (error_quark == 0)
773 error_quark = g_quark_from_static_string ("g-regex-error-quark");
782 * Increases reference count of @regex by 1.
789 g_regex_ref (GRegex *regex)
791 g_return_val_if_fail (regex != NULL, NULL);
792 g_atomic_int_inc ((gint*) ®ex->ref_count);
800 * Decreases reference count of @regex by 1. When reference count drops
801 * to zero, it frees all the memory associated with the regex structure.
806 g_regex_unref (GRegex *regex)
808 g_return_if_fail (regex != NULL);
810 if (g_atomic_int_exchange_and_add ((gint *) ®ex->ref_count, -1) - 1 == 0)
812 g_free (regex->pattern);
813 if (regex->pcre_re != NULL)
814 pcre_free (regex->pcre_re);
815 if (regex->extra != NULL)
816 pcre_free (regex->extra);
823 * @pattern: the regular expression
824 * @compile_options: compile options for the regular expression
825 * @match_options: match options for the regular expression
826 * @error: return location for a #GError
828 * Compiles the regular expression to an internal form, and does the initial
829 * setup of the #GRegex structure.
831 * Returns: a #GRegex structure. Call g_regex_unref() when you are done
837 g_regex_new (const gchar *pattern,
838 GRegexCompileFlags compile_options,
839 GRegexMatchFlags match_options,
846 gboolean optimize = FALSE;
847 static gboolean initialized = FALSE;
849 g_return_val_if_fail (pattern != NULL, NULL);
850 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
851 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
852 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
859 pcre_config (PCRE_CONFIG_UTF8, &support);
862 msg = N_("PCRE library is compiled without UTF8 support");
864 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
868 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
871 msg = N_("PCRE library is compiled without UTF8 properties support");
873 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
880 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
881 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
882 if (compile_options & G_REGEX_OPTIMIZE)
885 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
886 * instead uses UTF-8 only if required with PCRE_UTF8. */
887 if (compile_options & G_REGEX_RAW)
890 compile_options &= ~G_REGEX_RAW;
895 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
896 match_options |= PCRE_NO_UTF8_CHECK;
899 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
900 * not for the system one. */
901 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
902 !(compile_options & G_REGEX_NEWLINE_LF))
904 compile_options |= PCRE_NEWLINE_ANY;
907 /* compile the pattern */
908 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
910 /* if the compilation failed, set the error member and return
914 GError *tmp_error = g_error_new (G_REGEX_ERROR,
915 G_REGEX_ERROR_COMPILE,
916 _("Error while compiling regular "
917 "expression %s at char %d: %s"),
918 pattern, erroffset, errmsg);
919 g_propagate_error (error, tmp_error);
924 regex = g_new0 (GRegex, 1);
925 regex->ref_count = 1;
926 regex->pattern = g_strdup (pattern);
928 regex->compile_opts = compile_options;
929 regex->match_opts = match_options;
933 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
936 GError *tmp_error = g_error_new (G_REGEX_ERROR,
937 G_REGEX_ERROR_OPTIMIZE,
938 _("Error while optimizing "
939 "regular expression %s: %s"),
942 g_propagate_error (error, tmp_error);
951 * g_regex_get_pattern:
952 * @regex: a #GRegex structure
954 * Gets the pattern string associated with @regex, i.e. a copy of
955 * the string passed to g_regex_new().
957 * Returns: the pattern of @regex
962 g_regex_get_pattern (const GRegex *regex)
964 g_return_val_if_fail (regex != NULL, NULL);
966 return regex->pattern;
970 * g_regex_get_max_backref:
973 * Returns the number of the highest back reference
974 * in the pattern, or 0 if the pattern does not contain
977 * Returns: the number of the highest back reference.
982 g_regex_get_max_backref (const GRegex *regex)
986 pcre_fullinfo (regex->pcre_re, regex->extra,
987 PCRE_INFO_BACKREFMAX, &value);
993 * g_regex_get_capture_count:
996 * Returns the number of capturing subpatterns in the pattern.
998 * Returns: the number of capturing subpatterns.
1003 g_regex_get_capture_count (const GRegex *regex)
1007 pcre_fullinfo (regex->pcre_re, regex->extra,
1008 PCRE_INFO_CAPTURECOUNT, &value);
1014 * g_regex_match_simple:
1015 * @pattern: the regular expression
1016 * @string: the string to scan for matches
1017 * @compile_options: compile options for the regular expression
1018 * @match_options: match options
1020 * Scans for a match in @string for @pattern.
1022 * This function is equivalent to g_regex_match() but it does not
1023 * require to compile the pattern with g_regex_new(), avoiding some
1024 * lines of code when you need just to do a match without extracting
1025 * substrings, capture counts, and so on.
1027 * If this function is to be called on the same @pattern more than
1028 * once, it's more efficient to compile the pattern once with
1029 * g_regex_new() and then use g_regex_match().
1031 * Returns: %TRUE is the string matched, %FALSE otherwise
1036 g_regex_match_simple (const gchar *pattern,
1037 const gchar *string,
1038 GRegexCompileFlags compile_options,
1039 GRegexMatchFlags match_options)
1044 regex = g_regex_new (pattern, compile_options, 0, NULL);
1047 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1048 g_regex_unref (regex);
1054 * @regex: a #GRegex structure from g_regex_new()
1055 * @string: the string to scan for matches
1056 * @match_options: match options
1057 * @match_info: pointer to location where to store the #GMatchInfo, or
1058 * %NULL if you do not need it
1060 * Scans for a match in string for the pattern in @regex. The @match_options
1061 * are combined with the match options specified when the @regex structure
1062 * was created, letting you have more flexibility in reusing #GRegex
1065 * A #GMatchInfo structure, used to get information on the match, is stored
1066 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1067 * it is created even if the function returns %FALSE, i.e. you must free it
1068 * regardless if regular expression actually matched.
1070 * To retrieve all the non-overlapping matches of the pattern in string you
1071 * can use g_match_info_next().
1073 * <informalexample><programlisting>
1075 * print_uppercase_words (const gchar *string)
1077 * /* Print all uppercase-only words. */
1079 * GMatchInfo *match_info;
1081 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1082 * g_regex_match (regex, string, 0, &match_info);
1083 * while (g_match_info_matches (match_info))
1085 * gchar *word = g_match_info_fetch (match_info, 0);
1086 * g_print ("Found: %s\n", word);
1088 * g_match_info_next (match_info, NULL);
1090 * g_match_info_free (match_info);
1091 * g_regex_unref (regex);
1093 * </programlisting></informalexample>
1095 * Returns: %TRUE is the string matched, %FALSE otherwise
1100 g_regex_match (const GRegex *regex,
1101 const gchar *string,
1102 GRegexMatchFlags match_options,
1103 GMatchInfo **match_info)
1105 return g_regex_match_full (regex, string, -1, 0, match_options,
1110 * g_regex_match_full:
1111 * @regex: a #GRegex structure from g_regex_new()
1112 * @string: the string to scan for matches
1113 * @string_len: the length of @string, or -1 if @string is nul-terminated
1114 * @start_position: starting index of the string to match
1115 * @match_options: match options
1116 * @match_info: pointer to location where to store the #GMatchInfo, or
1117 * %NULL if you do not need it
1118 * @error: location to store the error occuring, or %NULL to ignore errors
1120 * Scans for a match in string for the pattern in @regex. The @match_options
1121 * are combined with the match options specified when the @regex structure
1122 * was created, letting you have more flexibility in reusing #GRegex
1125 * Setting @start_position differs from just passing over a shortened string
1126 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1127 * with any kind of lookbehind assertion, such as "\b".
1129 * A #GMatchInfo structure, used to get information on the match, is stored
1130 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1131 * it is created even if the function returns %FALSE, i.e. you must free it
1132 * regardless if regular expression actually matched.
1134 * @string is not copied and is used in #GMatchInfo internally. If you use
1135 * any #GMatchInfo method (except g_match_info_free()) after freeing or
1136 * modifying @string then the behaviour is undefined.
1138 * To retrieve all the non-overlapping matches of the pattern in string you
1139 * can use g_match_info_next().
1141 * <informalexample><programlisting>
1143 * print_uppercase_words (const gchar *string)
1145 * /* Print all uppercase-only words. */
1147 * GMatchInfo *match_info;
1148 * GError *error = NULL;
1150 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1151 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1152 * while (g_match_info_matches (match_info))
1154 * gchar *word = g_match_info_fetch (match_info, 0);
1155 * g_print ("Found: %s\n", word);
1157 * g_match_info_next (match_info, &error);
1159 * g_match_info_free (match_info);
1160 * g_regex_unref (regex);
1161 * if (error != NULL)
1163 * g_printerr ("Error while matching: %s\n", error->message);
1164 * g_error_free (error);
1167 * </programlisting></informalexample>
1169 * Returns: %TRUE is the string matched, %FALSE otherwise
1174 g_regex_match_full (const GRegex *regex,
1175 const gchar *string,
1177 gint start_position,
1178 GRegexMatchFlags match_options,
1179 GMatchInfo **match_info,
1185 g_return_val_if_fail (regex != NULL, FALSE);
1186 g_return_val_if_fail (string != NULL, FALSE);
1187 g_return_val_if_fail (start_position >= 0, FALSE);
1188 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1189 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1191 info = match_info_new (regex, string, string_len, start_position,
1192 match_options, FALSE);
1193 match_ok = g_match_info_next (info, error);
1194 if (match_info != NULL)
1197 g_match_info_free (info);
1203 * g_regex_match_all:
1204 * @regex: a #GRegex structure from g_regex_new()
1205 * @string: the string to scan for matches
1206 * @match_options: match options
1207 * @match_info: pointer to location where to store the #GMatchInfo, or
1208 * %NULL if you do not need it
1210 * Using the standard algorithm for regular expression matching only the
1211 * longest match in the string is retrieved. This function uses a
1212 * different algorithm so it can retrieve all the possible matches.
1213 * For more documentation see g_regex_match_all_full().
1215 * A #GMatchInfo structure, used to get information on the match, is stored
1216 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1217 * it is created even if the function returns %FALSE, i.e. you must free it
1218 * regardless if regular expression actually matched.
1220 * Returns: %TRUE is the string matched, %FALSE otherwise
1225 g_regex_match_all (const GRegex *regex,
1226 const gchar *string,
1227 GRegexMatchFlags match_options,
1228 GMatchInfo **match_info)
1230 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1235 * g_regex_match_all_full:
1236 * @regex: a #GRegex structure from g_regex_new()
1237 * @string: the string to scan for matches
1238 * @string_len: the length of @string, or -1 if @string is nul-terminated
1239 * @start_position: starting index of the string to match
1240 * @match_options: match options
1241 * @match_info: pointer to location where to store the #GMatchInfo, or
1242 * %NULL if you do not need it
1243 * @error: location to store the error occuring, or %NULL to ignore errors
1245 * Using the standard algorithm for regular expression matching only the
1246 * longest match in the string is retrieved, it is not possibile to obtain
1247 * all the available matches. For instance matching
1248 * "<a> <b> <c>" against the pattern "<.*>" you get
1249 * "<a> <b> <c>".
1251 * This function uses a different algorithm (called DFA, i.e. deterministic
1252 * finite automaton), so it can retrieve all the possible matches, all
1253 * starting at the same point in the string. For instance matching
1254 * "<a> <b> <c>" against the pattern "<.*>" you
1255 * would obtain three matches: "<a> <b> <c>",
1256 * "<a> <b>" and "<a>".
1258 * The number of matched strings is retrieved using
1259 * g_match_info_get_match_count().
1260 * To obtain the matched strings and their position you can use,
1261 * respectively, g_match_info_fetch() and g_match_info_fetch_pos(). Note that
1262 * the strings are returned in reverse order of length; that is, the longest
1263 * matching string is given first.
1265 * Note that the DFA algorithm is slower than the standard one and it is not
1266 * able to capture substrings, so backreferences do not work.
1268 * Setting @start_position differs from just passing over a shortened string
1269 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1270 * with any kind of lookbehind assertion, such as "\b".
1272 * A #GMatchInfo structure, used to get information on the match, is stored
1273 * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1274 * it is created even if the function returns %FALSE, i.e. you must free it
1275 * regardless if regular expression actually matched.
1277 * Returns: %TRUE is the string matched, %FALSE otherwise
1282 g_regex_match_all_full (const GRegex *regex,
1283 const gchar *string,
1285 gint start_position,
1286 GRegexMatchFlags match_options,
1287 GMatchInfo **match_info,
1293 g_return_val_if_fail (regex != NULL, FALSE);
1294 g_return_val_if_fail (string != NULL, FALSE);
1295 g_return_val_if_fail (start_position >= 0, FALSE);
1296 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1297 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1299 info = match_info_new (regex, string, string_len, start_position,
1300 match_options, TRUE);
1306 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1307 info->string, info->string_len,
1309 regex->match_opts | match_options,
1310 info->offsets, info->n_offsets,
1311 info->workspace, info->n_workspace);
1312 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1314 /* info->workspace is too small. */
1315 info->n_workspace *= 2;
1316 info->workspace = g_realloc (info->workspace,
1317 info->n_workspace * sizeof (gint));
1320 else if (info->matches == 0)
1322 /* info->offsets is too small. */
1323 info->n_offsets *= 2;
1324 info->offsets = g_realloc (info->offsets,
1325 info->n_offsets * sizeof (gint));
1328 else if (IS_PCRE_ERROR (info->matches))
1330 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1331 _("Error while matching regular expression %s: %s"),
1332 regex->pattern, match_error (info->matches));
1336 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1339 if (match_info != NULL)
1342 g_match_info_free (info);
1344 return info->matches >= 0;
1348 * g_regex_get_string_number:
1349 * @regex: #GRegex structure
1350 * @name: name of the subexpression
1352 * Retrieves the number of the subexpression named @name.
1354 * Returns: The number of the subexpression or -1 if @name does not exists
1359 g_regex_get_string_number (const GRegex *regex,
1364 g_return_val_if_fail (regex != NULL, -1);
1365 g_return_val_if_fail (name != NULL, -1);
1367 num = pcre_get_stringnumber (regex->pcre_re, name);
1368 if (num == PCRE_ERROR_NOSUBSTRING)
1375 * g_regex_split_simple:
1376 * @pattern: the regular expression
1377 * @string: the string to scan for matches
1378 * @compile_options: compile options for the regular expression
1379 * @match_options: match options
1381 * Breaks the string on the pattern, and returns an array of the tokens.
1382 * If the pattern contains capturing parentheses, then the text for each
1383 * of the substrings will also be returned. If the pattern does not match
1384 * anywhere in the string, then the whole string is returned as the first
1387 * This function is equivalent to g_regex_split() but it does not
1388 * require to compile the pattern with g_regex_new(), avoiding some
1389 * lines of code when you need just to do a split without extracting
1390 * substrings, capture counts, and so on.
1392 * If this function is to be called on the same @pattern more than
1393 * once, it's more efficient to compile the pattern once with
1394 * g_regex_new() and then use g_regex_split().
1396 * As a special case, the result of splitting the empty string "" is an
1397 * empty vector, not a vector containing a single string. The reason for
1398 * this special case is that being able to represent a empty vector is
1399 * typically more useful than consistent handling of empty elements. If
1400 * you do need to represent empty elements, you'll need to check for the
1401 * empty string before calling this function.
1403 * A pattern that can match empty strings splits @string into separate
1404 * characters wherever it matches the empty string between characters.
1405 * For example splitting "ab c" using as a separator "\s*", you will get
1408 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1413 g_regex_split_simple (const gchar *pattern,
1414 const gchar *string,
1415 GRegexCompileFlags compile_options,
1416 GRegexMatchFlags match_options)
1421 regex = g_regex_new (pattern, compile_options, 0, NULL);
1424 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1425 g_regex_unref (regex);
1431 * @regex: a #GRegex structure
1432 * @string: the string to split with the pattern
1433 * @match_options: match time option flags
1435 * Breaks the string on the pattern, and returns an array of the tokens.
1436 * If the pattern contains capturing parentheses, then the text for each
1437 * of the substrings will also be returned. If the pattern does not match
1438 * anywhere in the string, then the whole string is returned as the first
1441 * As a special case, the result of splitting the empty string "" is an
1442 * empty vector, not a vector containing a single string. The reason for
1443 * this special case is that being able to represent a empty vector is
1444 * typically more useful than consistent handling of empty elements. If
1445 * you do need to represent empty elements, you'll need to check for the
1446 * empty string before calling this function.
1448 * A pattern that can match empty strings splits @string into separate
1449 * characters wherever it matches the empty string between characters.
1450 * For example splitting "ab c" using as a separator "\s*", you will get
1453 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1458 g_regex_split (const GRegex *regex,
1459 const gchar *string,
1460 GRegexMatchFlags match_options)
1462 return g_regex_split_full (regex, string, -1, 0,
1463 match_options, 0, NULL);
1467 * g_regex_split_full:
1468 * @regex: a #GRegex structure
1469 * @string: the string to split with the pattern
1470 * @string_len: the length of @string, or -1 if @string is nul-terminated
1471 * @start_position: starting index of the string to match
1472 * @match_options: match time option flags
1473 * @max_tokens: the maximum number of tokens to split @string into. If this
1474 * is less than 1, the string is split completely
1475 * @error: return location for a #GError
1477 * Breaks the string on the pattern, and returns an array of the tokens.
1478 * If the pattern contains capturing parentheses, then the text for each
1479 * of the substrings will also be returned. If the pattern does not match
1480 * anywhere in the string, then the whole string is returned as the first
1483 * As a special case, the result of splitting the empty string "" is an
1484 * empty vector, not a vector containing a single string. The reason for
1485 * this special case is that being able to represent a empty vector is
1486 * typically more useful than consistent handling of empty elements. If
1487 * you do need to represent empty elements, you'll need to check for the
1488 * empty string before calling this function.
1490 * A pattern that can match empty strings splits @string into separate
1491 * characters wherever it matches the empty string between characters.
1492 * For example splitting "ab c" using as a separator "\s*", you will get
1495 * Setting @start_position differs from just passing over a shortened string
1496 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1497 * with any kind of lookbehind assertion, such as "\b".
1499 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1504 g_regex_split_full (const GRegex *regex,
1505 const gchar *string,
1507 gint start_position,
1508 GRegexMatchFlags match_options,
1512 GError *tmp_error = NULL;
1513 GMatchInfo *match_info;
1518 /* position of the last separator. */
1519 gint last_separator_end;
1520 /* was the last match 0 bytes long? */
1521 gboolean last_match_is_empty;
1522 /* the returned array of char **s */
1523 gchar **string_list;
1525 g_return_val_if_fail (regex != NULL, NULL);
1526 g_return_val_if_fail (string != NULL, NULL);
1527 g_return_val_if_fail (start_position >= 0, NULL);
1528 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1529 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1531 if (max_tokens <= 0)
1532 max_tokens = G_MAXINT;
1535 string_len = strlen (string);
1537 /* zero-length string */
1538 if (string_len - start_position == 0)
1539 return g_new0 (gchar *, 1);
1541 if (max_tokens == 1)
1543 string_list = g_new0 (gchar *, 2);
1544 string_list[0] = g_strndup (&string[start_position],
1545 string_len - start_position);
1551 last_separator_end = start_position;
1552 last_match_is_empty = FALSE;
1554 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1555 match_options, &match_info, &tmp_error);
1556 while (tmp_error == NULL)
1560 last_match_is_empty =
1561 (match_info->offsets[0] == match_info->offsets[1]);
1563 /* we need to skip empty separators at the same position of the end
1564 * of another separator. e.g. the string is "a b" and the separator
1565 * is " *", so from 1 to 2 we have a match and at position 2 we have
1566 * an empty match. */
1567 if (last_separator_end != match_info->offsets[1])
1572 token = g_strndup (string + last_separator_end,
1573 match_info->offsets[0] - last_separator_end);
1574 list = g_list_prepend (list, token);
1577 /* if there were substrings, these need to be added to
1579 match_count = g_match_info_get_match_count (match_info);
1580 if (match_count > 1)
1582 for (i = 1; i < match_count; i++)
1583 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1589 /* if there was no match, copy to end of string. */
1590 if (!last_match_is_empty)
1592 gchar *token = g_strndup (string + last_separator_end,
1593 match_info->string_len - last_separator_end);
1594 list = g_list_prepend (list, token);
1596 /* no more tokens, end the loop. */
1600 /* -1 to leave room for the last part. */
1601 if (token_count >= max_tokens - 1)
1603 /* we have reached the maximum number of tokens, so we copy
1604 * the remaining part of the string. */
1605 if (last_match_is_empty)
1607 /* the last match was empty, so we have moved one char
1608 * after the real position to avoid empty matches at the
1610 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1612 /* the if is needed in the case we have terminated the available
1613 * tokens, but we are at the end of the string, so there are no
1614 * characters left to copy. */
1615 if (string_len > match_info->pos)
1617 gchar *token = g_strndup (string + match_info->pos,
1618 string_len - match_info->pos);
1619 list = g_list_prepend (list, token);
1625 last_separator_end = match_info->pos;
1626 if (last_match_is_empty)
1627 /* if the last match was empty, g_match_info_next() has moved
1628 * forward to avoid infinite loops, but we still need to copy that
1630 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1632 match_ok = g_match_info_next (match_info, &tmp_error);
1634 g_match_info_free (match_info);
1635 if (tmp_error != NULL)
1637 g_propagate_error (error, tmp_error);
1638 g_list_foreach (list, (GFunc)g_free, NULL);
1640 match_info->pos = -1;
1644 string_list = g_new (gchar *, g_list_length (list) + 1);
1646 for (last = g_list_last (list); last; last = g_list_previous (last))
1647 string_list[i++] = last->data;
1657 REPL_TYPE_CHARACTER,
1658 REPL_TYPE_SYMBOLIC_REFERENCE,
1659 REPL_TYPE_NUMERIC_REFERENCE,
1660 REPL_TYPE_CHANGE_CASE
1665 CHANGE_CASE_NONE = 1 << 0,
1666 CHANGE_CASE_UPPER = 1 << 1,
1667 CHANGE_CASE_LOWER = 1 << 2,
1668 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1669 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1670 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1671 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1672 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1675 struct _InterpolationData
1681 ChangeCase change_case;
1685 free_interpolation_data (InterpolationData *data)
1687 g_free (data->text);
1691 static const gchar *
1692 expand_escape (const gchar *replacement,
1694 InterpolationData *data,
1699 const gchar *error_detail;
1701 GError *tmp_error = NULL;
1709 data->type = REPL_TYPE_CHARACTER;
1714 data->type = REPL_TYPE_CHARACTER;
1719 data->type = REPL_TYPE_CHARACTER;
1724 data->type = REPL_TYPE_CHARACTER;
1729 data->type = REPL_TYPE_CHARACTER;
1734 data->type = REPL_TYPE_CHARACTER;
1739 data->type = REPL_TYPE_CHARACTER;
1744 data->type = REPL_TYPE_CHARACTER;
1754 h = g_ascii_xdigit_value (*p);
1757 error_detail = _("hexadecimal digit or '}' expected");
1768 for (i = 0; i < 2; i++)
1770 h = g_ascii_xdigit_value (*p);
1773 error_detail = _("hexadecimal digit expected");
1780 data->type = REPL_TYPE_STRING;
1781 data->text = g_new0 (gchar, 8);
1782 g_unichar_to_utf8 (x, data->text);
1786 data->type = REPL_TYPE_CHANGE_CASE;
1787 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1791 data->type = REPL_TYPE_CHANGE_CASE;
1792 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1796 data->type = REPL_TYPE_CHANGE_CASE;
1797 data->change_case = CHANGE_CASE_LOWER;
1801 data->type = REPL_TYPE_CHANGE_CASE;
1802 data->change_case = CHANGE_CASE_UPPER;
1806 data->type = REPL_TYPE_CHANGE_CASE;
1807 data->change_case = CHANGE_CASE_NONE;
1813 error_detail = _("missing '<' in symbolic reference");
1822 error_detail = _("unfinished symbolic reference");
1829 error_detail = _("zero-length symbolic reference");
1832 if (g_ascii_isdigit (*q))
1837 h = g_ascii_digit_value (*q);
1840 error_detail = _("digit expected");
1849 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1856 if (!g_ascii_isalnum (*r))
1858 error_detail = _("illegal symbolic reference");
1865 data->text = g_strndup (q, p - q);
1866 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1871 /* if \0 is followed by a number is an octal number representing a
1872 * character, else it is a numeric reference. */
1873 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1876 p = g_utf8_next_char (p);
1889 for (i = 0; i < 3; i++)
1891 h = g_ascii_digit_value (*p);
1901 if (i == 2 && base == 10)
1907 if (base == 8 || i == 3)
1909 data->type = REPL_TYPE_STRING;
1910 data->text = g_new0 (gchar, 8);
1911 g_unichar_to_utf8 (x, data->text);
1915 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1920 error_detail = _("stray final '\\'");
1924 error_detail = _("unknown escape sequence");
1931 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1932 tmp_error = g_error_new (G_REGEX_ERROR,
1933 G_REGEX_ERROR_REPLACE,
1934 _("Error while parsing replacement "
1935 "text \"%s\" at char %lu: %s"),
1937 (gulong)(p - replacement),
1939 g_propagate_error (error, tmp_error);
1945 split_replacement (const gchar *replacement,
1949 InterpolationData *data;
1950 const gchar *p, *start;
1952 start = p = replacement;
1957 data = g_new0 (InterpolationData, 1);
1958 start = p = expand_escape (replacement, p, data, error);
1961 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1963 free_interpolation_data (data);
1967 list = g_list_prepend (list, data);
1972 if (*p == '\\' || *p == '\0')
1976 data = g_new0 (InterpolationData, 1);
1977 data->text = g_strndup (start, p - start);
1978 data->type = REPL_TYPE_STRING;
1979 list = g_list_prepend (list, data);
1985 return g_list_reverse (list);
1988 /* Change the case of c based on change_case. */
1989 #define CHANGE_CASE(c, change_case) \
1990 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
1991 g_unichar_tolower (c) : \
1992 g_unichar_toupper (c))
1995 string_append (GString *string,
1997 ChangeCase *change_case)
2001 if (text[0] == '\0')
2004 if (*change_case == CHANGE_CASE_NONE)
2006 g_string_append (string, text);
2008 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2010 c = g_utf8_get_char (text);
2011 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2012 g_string_append (string, g_utf8_next_char (text));
2013 *change_case = CHANGE_CASE_NONE;
2017 while (*text != '\0')
2019 c = g_utf8_get_char (text);
2020 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2021 text = g_utf8_next_char (text);
2027 interpolate_replacement (const GMatchInfo *match_info,
2032 InterpolationData *idata;
2034 ChangeCase change_case = CHANGE_CASE_NONE;
2036 for (list = data; list; list = list->next)
2039 switch (idata->type)
2041 case REPL_TYPE_STRING:
2042 string_append (result, idata->text, &change_case);
2044 case REPL_TYPE_CHARACTER:
2045 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2046 if (change_case & CHANGE_CASE_SINGLE_MASK)
2047 change_case = CHANGE_CASE_NONE;
2049 case REPL_TYPE_NUMERIC_REFERENCE:
2050 match = g_match_info_fetch (match_info, idata->num);
2053 string_append (result, match, &change_case);
2057 case REPL_TYPE_SYMBOLIC_REFERENCE:
2058 match = g_match_info_fetch_named (match_info, idata->text);
2061 string_append (result, match, &change_case);
2065 case REPL_TYPE_CHANGE_CASE:
2066 change_case = idata->change_case;
2074 /* whether actual match_info is needed for replacement, i.e.
2075 * whether there are references
2078 interpolation_list_needs_match (GList *list)
2080 while (list != NULL)
2082 InterpolationData *data = list->data;
2084 if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2085 data->type == REPL_TYPE_NUMERIC_REFERENCE)
2098 * @regex: a #GRegex structure
2099 * @string: the string to perform matches against
2100 * @string_len: the length of @string, or -1 if @string is nul-terminated
2101 * @start_position: starting index of the string to match
2102 * @replacement: text to replace each match with
2103 * @match_options: options for the match
2104 * @error: location to store the error occuring, or %NULL to ignore errors
2106 * Replaces all occurances of the pattern in @regex with the
2107 * replacement text. Backreferences of the form '\number' or '\g<number>'
2108 * in the replacement text are interpolated by the number-th captured
2109 * subexpression of the match, '\g<name>' refers to the captured subexpression
2110 * with the given name. '\0' refers to the complete match, but '\0' followed
2111 * by a number is the octal representation of a character. To include a
2112 * literal '\' in the replacement, write '\\'.
2113 * There are also escapes that changes the case of the following text:
2116 * <varlistentry><term>\l</term>
2118 * <para>Convert to lower case the next character</para>
2121 * <varlistentry><term>\u</term>
2123 * <para>Convert to upper case the next character</para>
2126 * <varlistentry><term>\L</term>
2128 * <para>Convert to lower case till \E</para>
2131 * <varlistentry><term>\U</term>
2133 * <para>Convert to upper case till \E</para>
2136 * <varlistentry><term>\E</term>
2138 * <para>End case modification</para>
2143 * If you do not need to use backreferences use g_regex_replace_literal().
2145 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2146 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2147 * you can use g_regex_replace_literal().
2149 * Setting @start_position differs from just passing over a shortened string
2150 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2151 * with any kind of lookbehind assertion, such as "\b".
2153 * Returns: a newly allocated string containing the replacements
2158 g_regex_replace (const GRegex *regex,
2159 const gchar *string,
2161 gint start_position,
2162 const gchar *replacement,
2163 GRegexMatchFlags match_options,
2168 GError *tmp_error = NULL;
2170 g_return_val_if_fail (regex != NULL, NULL);
2171 g_return_val_if_fail (string != NULL, NULL);
2172 g_return_val_if_fail (start_position >= 0, NULL);
2173 g_return_val_if_fail (replacement != NULL, NULL);
2174 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2175 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2177 list = split_replacement (replacement, &tmp_error);
2178 if (tmp_error != NULL)
2180 g_propagate_error (error, tmp_error);
2184 result = g_regex_replace_eval (regex,
2185 string, string_len, start_position,
2187 interpolate_replacement,
2190 if (tmp_error != NULL)
2191 g_propagate_error (error, tmp_error);
2193 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2200 literal_replacement (const GMatchInfo *match_info,
2204 g_string_append (result, data);
2209 * g_regex_replace_literal:
2210 * @regex: a #GRegex structure
2211 * @string: the string to perform matches against
2212 * @string_len: the length of @string, or -1 if @string is nul-terminated
2213 * @start_position: starting index of the string to match
2214 * @replacement: text to replace each match with
2215 * @match_options: options for the match
2216 * @error: location to store the error occuring, or %NULL to ignore errors
2218 * Replaces all occurances of the pattern in @regex with the
2219 * replacement text. @replacement is replaced literally, to
2220 * include backreferences use g_regex_replace().
2222 * Setting @start_position differs from just passing over a shortened string
2223 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2224 * with any kind of lookbehind assertion, such as "\b".
2226 * Returns: a newly allocated string containing the replacements
2231 g_regex_replace_literal (const GRegex *regex,
2232 const gchar *string,
2234 gint start_position,
2235 const gchar *replacement,
2236 GRegexMatchFlags match_options,
2239 g_return_val_if_fail (replacement != NULL, NULL);
2240 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2242 return g_regex_replace_eval (regex,
2243 string, string_len, start_position,
2245 literal_replacement,
2246 (gpointer)replacement,
2251 * g_regex_replace_eval:
2252 * @regex: a #GRegex structure from g_regex_new()
2253 * @string: string to perform matches against
2254 * @string_len: the length of @string, or -1 if @string is nul-terminated
2255 * @start_position: starting index of the string to match
2256 * @match_options: options for the match
2257 * @eval: a function to call for each match
2258 * @user_data: user data to pass to the function
2259 * @error: location to store the error occuring, or %NULL to ignore errors
2261 * Replaces occurances of the pattern in regex with the output of @eval
2262 * for that occurance.
2264 * Setting @start_position differs from just passing over a shortened string
2265 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2266 * with any kind of lookbehind assertion, such as "\b".
2268 * Returns: a newly allocated string containing the replacements
2273 g_regex_replace_eval (const GRegex *regex,
2274 const gchar *string,
2276 gint start_position,
2277 GRegexMatchFlags match_options,
2278 GRegexEvalCallback eval,
2282 GMatchInfo *match_info;
2285 gboolean done = FALSE;
2286 GError *tmp_error = NULL;
2288 g_return_val_if_fail (regex != NULL, NULL);
2289 g_return_val_if_fail (string != NULL, NULL);
2290 g_return_val_if_fail (start_position >= 0, NULL);
2291 g_return_val_if_fail (eval != NULL, NULL);
2292 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2295 string_len = strlen (string);
2297 result = g_string_sized_new (string_len);
2299 /* run down the string making matches. */
2300 g_regex_match_full (regex, string, string_len, start_position,
2301 match_options, &match_info, &tmp_error);
2302 while (!done && g_match_info_matches (match_info))
2304 g_string_append_len (result,
2306 match_info->offsets[0] - str_pos);
2307 done = (*eval) (match_info, result, user_data);
2308 str_pos = match_info->offsets[1];
2309 g_match_info_next (match_info, &tmp_error);
2311 g_match_info_free (match_info);
2312 if (tmp_error != NULL)
2314 g_propagate_error (error, tmp_error);
2315 g_string_free (result, TRUE);
2319 g_string_append_len (result, string + str_pos, string_len - str_pos);
2320 return g_string_free (result, FALSE);
2324 * g_regex_check_replacement:
2325 * @replacement: the replacement string
2326 * @has_references: location to store information about
2327 * references in @replacement or %NULL
2328 * @error: location to store error
2330 * Checks whether @replacement is a valid replacement string (see g_regex_replace()),
2331 * i.e. that all escape sequences in it are valid.
2333 * If @has_references is not %NULL then @replacement is checked for
2334 * pattern references. For instance, replacement text 'foo\n'
2335 * does not contain references and may be evaluated without information
2336 * about actual match, but '\0\1' (whole match followed by first subpattern)
2337 * requires valid #GMatchInfo object.
2339 * Returns: whether @replacement is a valid replacement string
2344 g_regex_check_replacement (const gchar *replacement,
2345 gboolean *has_references,
2351 list = split_replacement (replacement, &tmp);
2355 g_propagate_error (error, tmp);
2360 *has_references = interpolation_list_needs_match (list);
2362 g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2369 * g_regex_escape_string:
2370 * @string: the string to escape
2371 * @length: the length of @string, or -1 if @string is nul-terminated
2373 * Escapes the special characters used for regular expressions in @string,
2374 * for instance "a.b*c" becomes "a\.b\*c". This function is useful to
2375 * dynamically generate regular expressions.
2377 * @string can contain nul characters that are replaced with "\0", in this
2378 * case remember to specify the correct length of @string in @length.
2380 * Returns: a newly-allocated escaped string
2385 g_regex_escape_string (const gchar *string,
2389 const char *p, *piece_start, *end;
2391 g_return_val_if_fail (string != NULL, NULL);
2394 length = strlen (string);
2396 end = string + length;
2397 p = piece_start = string;
2398 escaped = g_string_sized_new (length + 1);
2419 if (p != piece_start)
2420 /* copy the previous piece. */
2421 g_string_append_len (escaped, piece_start, p - piece_start);
2422 g_string_append_c (escaped, '\\');
2424 g_string_append_c (escaped, '0');
2426 g_string_append_c (escaped, *p);
2430 p = g_utf8_next_char (p);
2435 if (piece_start < end)
2436 g_string_append_len (escaped, piece_start, end - piece_start);
2438 return g_string_free (escaped, FALSE);
2441 #define __G_REGEX_C__
2442 #include "galiasdef.c"