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 static GRegex *regex_ref (GRegex *regex);
102 static void regex_unref (GRegex *regex);
104 typedef struct _InterpolationData InterpolationData;
105 static gboolean interpolate_replacement (const GRegex *regex,
106 const GMatchInfo *match_info,
110 static GList *split_replacement (const gchar *replacement,
112 static void free_interpolation_data (InterpolationData *data);
116 match_error (gint errcode)
120 case PCRE_ERROR_NOMATCH:
123 case PCRE_ERROR_NULL:
124 /* NULL argument, this should not happen in GRegex */
125 g_warning ("A NULL argument was passed to PCRE");
127 case PCRE_ERROR_BADOPTION:
128 return "bad options";
129 case PCRE_ERROR_BADMAGIC:
130 return _("corrupted object");
131 case PCRE_ERROR_UNKNOWN_OPCODE:
132 return N_("internal error or corrupted object");
133 case PCRE_ERROR_NOMEMORY:
134 return _("out of memory");
135 case PCRE_ERROR_NOSUBSTRING:
136 /* not used by pcre_exec() */
138 case PCRE_ERROR_MATCHLIMIT:
139 return _("backtracking limit reached");
140 case PCRE_ERROR_CALLOUT:
141 /* callouts are not implemented */
143 case PCRE_ERROR_BADUTF8:
144 case PCRE_ERROR_BADUTF8_OFFSET:
145 /* we do not check if strings are valid */
147 case PCRE_ERROR_PARTIAL:
150 case PCRE_ERROR_BADPARTIAL:
151 return _("the pattern contains items not supported for partial matching");
152 case PCRE_ERROR_INTERNAL:
153 return _("internal error");
154 case PCRE_ERROR_BADCOUNT:
155 /* negative ovecsize, this should not happen in GRegex */
156 g_warning ("A negative ovecsize was passed to PCRE");
158 case PCRE_ERROR_DFA_UITEM:
159 return _("the pattern contains items not supported for partial matching");
160 case PCRE_ERROR_DFA_UCOND:
161 return _("back references as conditions are not supported for partial matching");
162 case PCRE_ERROR_DFA_UMLIMIT:
163 /* the match_field field is not used in GRegex */
165 case PCRE_ERROR_DFA_WSSIZE:
166 /* handled expanding the workspace */
168 case PCRE_ERROR_DFA_RECURSE:
169 case PCRE_ERROR_RECURSIONLIMIT:
170 return _("recursion limit reached");
171 case PCRE_ERROR_NULLWSLIMIT:
172 return _("workspace limit for empty substrings reached");
173 case PCRE_ERROR_BADNEWLINE:
174 return _("invalid combination of newline flags");
178 return _("unknown error");
185 match_info_new (const GRegex *regex,
192 GMatchInfo *match_info;
195 string_len = strlen (string);
197 match_info = g_new0 (GMatchInfo, 1);
198 match_info->regex = regex_ref ((GRegex *)regex);
199 match_info->string = string;
200 match_info->string_len = string_len;
201 match_info->matches = PCRE_ERROR_NOMATCH;
202 match_info->pos = start_position;
203 match_info->match_opts = match_options;
207 /* These values should be enough for most cases, if they are not
208 * enough g_regex_match_all_full() will expand them. */
209 match_info->n_offsets = 24;
210 match_info->n_workspace = 100;
211 match_info->workspace = g_new (gint, match_info->n_workspace);
216 pcre_fullinfo (regex->pcre_re, regex->extra,
217 PCRE_INFO_CAPTURECOUNT, &capture_count);
218 match_info->n_offsets = (capture_count + 1) * 3;
220 match_info->offsets = g_new0 (gint, match_info->n_offsets);
227 * @match_info: a #GMatchInfo
229 * Frees all the memory associated with the #GMatchInfo structure.
234 g_match_info_free (GMatchInfo *match_info)
236 regex_unref (match_info->regex);
237 g_free (match_info->offsets);
238 g_free (match_info->workspace);
244 * @match_info: a #GMatchInfo structure
245 * @error: location to store the error occuring, or NULL to ignore errors
247 * Scans for the next match using the same parameters of the previous
248 * call to g_regex_match_full() or g_regex_match() that returned
251 * The match is done on the string passed to the match function, so you
252 * cannot free it before calling this function.
254 * Returns: %TRUE is the string matched, %FALSE otherwise
259 g_match_info_next (GMatchInfo *match_info,
262 g_return_val_if_fail (match_info != NULL, FALSE);
263 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
264 g_return_val_if_fail (match_info->pos >= 0, FALSE);
266 match_info->matches = pcre_exec (match_info->regex->pcre_re,
267 match_info->regex->extra,
269 match_info->string_len,
271 match_info->regex->match_opts |
272 match_info->match_opts,
274 match_info->n_offsets);
275 if (IS_PCRE_ERROR (match_info->matches))
277 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
278 _("Error while matching regular expression %s: %s"),
279 match_info->regex->pattern, match_error (match_info->matches));
283 /* avoid infinite loops if the pattern is an empty string or something
285 if (match_info->pos == match_info->offsets[1])
287 if (match_info->pos > match_info->string_len)
289 /* we have reached the end of the string */
290 match_info->pos = -1;
291 match_info->matches = PCRE_ERROR_NOMATCH;
294 match_info->pos = NEXT_CHAR (match_info->regex,
295 &match_info->string[match_info->pos]) -
300 match_info->pos = match_info->offsets[1];
303 return match_info->matches >= 0;
307 * g_match_info_matches:
308 * @match_info: a #GMatchInfo structure
310 * Returns: %TRUE if the previous match operation succeeded, %FALSE
316 g_match_info_matches (const GMatchInfo *match_info)
318 g_return_val_if_fail (match_info != NULL, FALSE);
320 return match_info->matches >= 0;
324 * g_match_info_get_match_count:
325 * @match_info: a #GMatchInfo structure
327 * Retrieves the number of matched substrings (including substring 0, that
328 * is the whole matched text), so 1 is returned if the pattern has no
329 * substrings in it and 0 is returned if the match failed.
331 * If the last match was obtained using the DFA algorithm, that is using
332 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
333 * count is not that of the number of capturing parentheses but that of
334 * the number of matched substrings.
336 * Returns: Number of matched substrings, or -1 if an error occurred
341 g_match_info_get_match_count (const GMatchInfo *match_info)
343 g_return_val_if_fail (match_info, -1);
345 if (match_info->matches == PCRE_ERROR_NOMATCH)
348 else if (match_info->matches < PCRE_ERROR_NOMATCH)
353 return match_info->matches;
357 * g_match_info_is_partial_match:
358 * @match_info: a #GMatchInfo structure
360 * Usually if the string passed to g_regex_match*() matches as far as
361 * it goes, but is too short to match the entire pattern, %FALSE is
362 * returned. There are circumstances where it might be helpful to
363 * distinguish this case from other cases in which there is no match.
365 * Consider, for example, an application where a human is required to
366 * type in data for a field with specific formatting requirements. An
367 * example might be a date in the form ddmmmyy, defined by the pattern
368 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
369 * If the application sees the user’s keystrokes one by one, and can
370 * check that what has been typed so far is potentially valid, it is
371 * able to raise an error as soon as a mistake is made.
373 * GRegex supports the concept of partial matching by means of the
374 * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
375 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
376 * for a complete match, %FALSE otherwise. But, when this functions
377 * returns %FALSE, you can check if the match was partial calling
378 * g_match_info_is_partial_match().
380 * When using partial matching you cannot use g_match_info_fetch*().
382 * Because of the way certain internal optimizations are implemented the
383 * partial matching algorithm cannot be used with all patterns. So repeated
384 * single characters such as "a{2,4}" and repeated single metasequences such
385 * as "\d+" are not permitted if the maximum number of occurrences is
386 * greater than one. Optional items such as "\d?" (where the maximum is one)
387 * are permitted. Quantifiers with any values are permitted after
388 * parentheses, so the invalid examples above can be coded thus "(a){2,4}"
389 * and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set for a pattern that does
390 * not conform to the restrictions, matching functions return an error.
392 * Returns: %TRUE if the match was partial, %FALSE otherwise
397 g_match_info_is_partial_match (const GMatchInfo *match_info)
399 g_return_val_if_fail (match_info != NULL, FALSE);
401 return match_info->matches == PCRE_ERROR_PARTIAL;
405 * g_match_info_expand_references:
406 * @match_info: a #GMatchInfo
407 * @string_to_expand: the string to expand
408 * @error: location to store the error occuring, or %NULL to ignore errors
410 * Returns a new string containing the text in @string_to_expand with
411 * references expanded. References refer to the last match done with
412 * @string against @regex and have the same syntax used by g_regex_replace().
414 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
415 * passed to g_regex_new().
417 * The backreferences are extracted from the string passed to the match
418 * function, so you cannot free it before calling this function.
420 * Returns: the expanded string, or %NULL if an error occurred
425 g_match_info_expand_references (const GMatchInfo *match_info,
426 const gchar *string_to_expand,
431 GError *tmp_error = NULL;
433 g_return_val_if_fail (match_info != NULL, NULL);
434 g_return_val_if_fail (string_to_expand != NULL, NULL);
435 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
437 list = split_replacement (string_to_expand, &tmp_error);
438 if (tmp_error != NULL)
440 g_propagate_error (error, tmp_error);
444 result = g_string_sized_new (strlen (string_to_expand));
445 interpolate_replacement (match_info->regex, match_info,
446 match_info->string, result, list);
448 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
451 return g_string_free (result, FALSE);
455 * g_match_info_fetch:
456 * @match_info: #GMatchInfo structure
457 * @match_num: number of the sub expression
459 * Retrieves the text matching the @match_num<!-- -->'th capturing parentheses.
460 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
463 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
464 * sub pattern 1, matching "b" against "(a)?b") then an empty string is
467 * If the match was obtained using the DFA algorithm, that is using
468 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
469 * string is not that of a set of parentheses but that of a matched
470 * substring. Substrings are matched in reverse order of length, so 0 is
473 * The string is fetched from the string passed to the match function,
474 * so you cannot free it before calling this function.
476 * Returns: The matched substring, or %NULL if an error occurred.
477 * You have to free the string yourself
482 g_match_info_fetch (const GMatchInfo *match_info,
485 /* we cannot use pcre_get_substring() because it allocates the
486 * string using pcre_malloc(). */
490 g_return_val_if_fail (match_info != NULL, NULL);
491 g_return_val_if_fail (match_num >= 0, NULL);
493 /* match_num does not exist or it didn't matched, i.e. matching "b"
494 * against "(a)?b" then group 0 is empty. */
495 if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
497 else if (start == -1)
498 match = g_strdup ("");
500 match = g_strndup (&match_info->string[start], end - start);
506 * g_match_info_fetch_pos:
507 * @match_info: #GMatchInfo structure
508 * @match_num: number of the sub expression
509 * @start_pos: pointer to location where to store the start position
510 * @end_pos: pointer to location where to store the end position
512 * Retrieves the position of the @match_num<!-- -->'th capturing parentheses.
513 * 0 is the full text of the match, 1 is the first paren set, 2 the second,
516 * If @match_num is a valid sub pattern but it didn't match anything (e.g.
517 * sub pattern 1, matching "b" against "(a)?b") then @start_pos and @end_pos
518 * are set to -1 and %TRUE is returned.
520 * If the match was obtained using the DFA algorithm, that is using
521 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
522 * position is not that of a set of parentheses but that of a matched
523 * substring. Substrings are matched in reverse order of length, so 0 is
526 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
527 * position cannot be fetched, @start_pos and @end_pos are left
533 g_match_info_fetch_pos (const GMatchInfo *match_info,
538 g_return_val_if_fail (match_info != NULL, FALSE);
539 g_return_val_if_fail (match_num >= 0, FALSE);
541 /* make sure the sub expression number they're requesting is less than
542 * the total number of sub expressions that were matched. */
543 if (match_num >= match_info->matches)
546 if (start_pos != NULL)
547 *start_pos = match_info->offsets[2 * match_num];
550 *end_pos = match_info->offsets[2 * match_num + 1];
556 * g_match_info_fetch_named:
557 * @match_info: #GMatchInfo structure
558 * @name: name of the subexpression
560 * Retrieves the text matching the capturing parentheses named @name.
562 * If @name is a valid sub pattern name but it didn't match anything (e.g.
563 * sub pattern "X", matching "b" against "(?P<X>a)?b") then an empty
564 * string is returned.
566 * The string is fetched from the string passed to the match function,
567 * so you cannot free it before calling this function.
569 * Returns: The matched substring, or %NULL if an error occurred.
570 * You have to free the string yourself
575 g_match_info_fetch_named (const GMatchInfo *match_info,
578 /* we cannot use pcre_get_named_substring() because it allocates the
579 * string using pcre_malloc(). */
582 g_return_val_if_fail (match_info != NULL, NULL);
583 g_return_val_if_fail (name != NULL, NULL);
585 num = g_regex_get_string_number (match_info->regex, name);
589 return g_match_info_fetch (match_info, num);
593 * g_match_info_fetch_named_pos:
594 * @match_info: #GMatchInfo structure
595 * @name: name of the subexpression
596 * @start_pos: pointer to location where to store the start position
597 * @end_pos: pointer to location where to store the end position
599 * Retrieves the position of the capturing parentheses named @name.
601 * If @name is a valid sub pattern name but it didn't match anything (e.g.
602 * sub pattern "X", matching "b" against "(?P<X>a)?b") then @start_pos and
603 * @end_pos are set to -1 and %TRUE is returned.
605 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
606 * position cannot be fetched, @start_pos and @end_pos are left
612 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
619 g_return_val_if_fail (match_info != NULL, FALSE);
620 g_return_val_if_fail (name != NULL, FALSE);
622 num = g_regex_get_string_number (match_info->regex, name);
626 return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
630 * g_match_info_fetch_all:
631 * @match_info: a #GMatchInfo structure
633 * Bundles up pointers to each of the matching substrings from a match
634 * and stores them in an array of gchar pointers. The first element in
635 * the returned array is the match number 0, i.e. the entire matched
638 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
639 * "b" against "(a)?b") then an empty string is inserted.
641 * If the last match was obtained using the DFA algorithm, that is using
642 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
643 * strings are not that matched by sets of parentheses but that of the
644 * matched substring. Substrings are matched in reverse order of length,
645 * so the first one is the longest match.
647 * The strings are fetched from the string passed to the match function,
648 * so you cannot free it before calling this function.
650 * Returns: a %NULL-terminated array of gchar * pointers. It must be freed
651 * using g_strfreev(). If the previous match failed %NULL is
657 g_match_info_fetch_all (const GMatchInfo *match_info)
659 /* we cannot use pcre_get_substring_list() because the returned value
660 * isn't suitable for g_strfreev(). */
664 g_return_val_if_fail (match_info != NULL, FALSE);
666 if (match_info->matches < 0)
669 result = g_new (gchar *, match_info->matches + 1);
670 for (i = 0; i < match_info->matches; i++)
671 result[i] = g_match_info_fetch (match_info, i);
681 g_regex_error_quark (void)
683 static GQuark error_quark = 0;
685 if (error_quark == 0)
686 error_quark = g_quark_from_static_string ("g-regex-error-quark");
692 regex_ref (GRegex *regex)
694 g_atomic_int_inc ((gint*) ®ex->ref_count);
699 regex_unref (GRegex *regex)
701 if (g_atomic_int_exchange_and_add ((gint *) ®ex->ref_count, -1) - 1 == 0)
703 g_free (regex->pattern);
704 if (regex->pcre_re != NULL)
705 pcre_free (regex->pcre_re);
706 if (regex->extra != NULL)
707 pcre_free (regex->extra);
714 * @pattern: the regular expression
715 * @compile_options: compile options for the regular expression
716 * @match_options: match options for the regular expression
717 * @error: return location for a #GError
719 * Compiles the regular expression to an internal form, and does the initial
720 * setup of the #GRegex structure.
722 * Returns: a #GRegex structure
727 g_regex_new (const gchar *pattern,
728 GRegexCompileFlags compile_options,
729 GRegexMatchFlags match_options,
736 gboolean optimize = FALSE;
737 static gboolean initialized = FALSE;
739 g_return_val_if_fail (pattern != NULL, NULL);
740 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
741 g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
742 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
749 pcre_config (PCRE_CONFIG_UTF8, &support);
752 msg = N_("PCRE library is compiled without UTF8 support");
754 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
758 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
761 msg = N_("PCRE library is compiled without UTF8 properties support");
763 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
770 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
771 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
772 if (compile_options & G_REGEX_OPTIMIZE)
775 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
776 * instead uses UTF-8 only if required with PCRE_UTF8. */
777 if (compile_options & G_REGEX_RAW)
780 compile_options &= ~G_REGEX_RAW;
785 compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
786 match_options |= PCRE_NO_UTF8_CHECK;
789 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
790 * not for the system one. */
791 if (!(compile_options & G_REGEX_NEWLINE_CR) &&
792 !(compile_options & G_REGEX_NEWLINE_LF))
794 compile_options |= PCRE_NEWLINE_ANY;
797 /* compile the pattern */
798 re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
800 /* if the compilation failed, set the error member and return
804 GError *tmp_error = g_error_new (G_REGEX_ERROR,
805 G_REGEX_ERROR_COMPILE,
806 _("Error while compiling regular "
807 "expression %s at char %d: %s"),
808 pattern, erroffset, errmsg);
809 g_propagate_error (error, tmp_error);
814 regex = g_new0 (GRegex, 1);
815 regex->ref_count = 1;
816 regex->pattern = g_strdup (pattern);
818 regex->compile_opts = compile_options;
819 regex->match_opts = match_options;
823 regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
826 GError *tmp_error = g_error_new (G_REGEX_ERROR,
827 G_REGEX_ERROR_OPTIMIZE,
828 _("Error while optimizing "
829 "regular expression %s: %s"),
832 g_propagate_error (error, tmp_error);
844 * Frees all the memory associated with the regex structure.
849 g_regex_free (GRegex *regex)
858 * g_regex_get_pattern:
859 * @regex: a #GRegex structure
861 * Gets the pattern string associated with @regex, i.e. a copy of
862 * the string passed to g_regex_new().
864 * Returns: the pattern of @regex
869 g_regex_get_pattern (const GRegex *regex)
871 g_return_val_if_fail (regex != NULL, NULL);
873 return regex->pattern;
877 * g_regex_get_max_backref:
880 * Returns the number of the highest back reference
881 * in the pattern, or 0 if the pattern does not contain
884 * Returns: the number of the highest back reference.
889 g_regex_get_max_backref (const GRegex *regex)
893 pcre_fullinfo (regex->pcre_re, regex->extra,
894 PCRE_INFO_BACKREFMAX, &value);
900 * g_regex_get_capture_count:
903 * Returns the number of capturing subpatterns in the pattern.
905 * Returns: the number of capturing subpatterns.
910 g_regex_get_capture_count (const GRegex *regex)
914 pcre_fullinfo (regex->pcre_re, regex->extra,
915 PCRE_INFO_CAPTURECOUNT, &value);
921 * g_regex_match_simple:
922 * @pattern: the regular expression
923 * @string: the string to scan for matches
924 * @compile_options: compile options for the regular expression
925 * @match_options: match options
927 * Scans for a match in @string for @pattern.
929 * This function is equivalent to g_regex_match() but it does not
930 * require to compile the pattern with g_regex_new(), avoiding some
931 * lines of code when you need just to do a match without extracting
932 * substrings, capture counts, and so on.
934 * If this function is to be called on the same @pattern more than
935 * once, it's more efficient to compile the pattern once with
936 * g_regex_new() and then use g_regex_match().
938 * Returns: %TRUE is the string matched, %FALSE otherwise
943 g_regex_match_simple (const gchar *pattern,
945 GRegexCompileFlags compile_options,
946 GRegexMatchFlags match_options)
951 regex = g_regex_new (pattern, compile_options, 0, NULL);
954 result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
955 g_regex_free (regex);
961 * @regex: a #GRegex structure from g_regex_new()
962 * @string: the string to scan for matches
963 * @match_options: match options
964 * @match_info: pointer to location where to store the #GMatchInfo, or
965 * %NULL if you do not nedd it
967 * Scans for a match in string for the pattern in @regex. The @match_options
968 * are combined with the match options specified when the @regex structure
969 * was created, letting you have more flexibility in reusing #GRegex
972 * A #GMatchInfo structure, used to get information on the match, is stored
973 * in @match_info if not %NULL.
975 * To retrieve all the non-overlapping matches of the pattern in string you
976 * can use g_match_info_next().
978 * <informalexample><programlisting>
980 * print_uppercase_words (const gchar *string)
982 * /* Print all uppercase-only words. */
984 * GMatchInfo *match_info;
986 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
987 * g_regex_match (regex, string, 0, &match_info);
988 * while (g_match_info_matches (match_info))
990 * gchar *word = g_match_info_fetch (match_info, 0);
991 * g_print ("Found: %s\n", word);
993 * g_match_info_next (match_info, NULL);
995 * g_match_info_free (match_info);
996 * g_regex_free (regex);
998 * </programlisting></informalexample>
1000 * Returns: %TRUE is the string matched, %FALSE otherwise
1005 g_regex_match (const GRegex *regex,
1006 const gchar *string,
1007 GRegexMatchFlags match_options,
1008 GMatchInfo **match_info)
1010 return g_regex_match_full (regex, string, -1, 0, match_options,
1015 * g_regex_match_full:
1016 * @regex: a #GRegex structure from g_regex_new()
1017 * @string: the string to scan for matches
1018 * @string_len: the length of @string, or -1 if @string is nul-terminated
1019 * @start_position: starting index of the string to match
1020 * @match_options: match options
1021 * @match_info: pointer to location where to store the #GMatchInfo, or
1022 * %NULL if you do not nedd it
1023 * @error: location to store the error occuring, or %NULL to ignore errors
1025 * Scans for a match in string for the pattern in @regex. The @match_options
1026 * are combined with the match options specified when the @regex structure
1027 * was created, letting you have more flexibility in reusing #GRegex
1030 * Setting @start_position differs from just passing over a shortened string
1031 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1032 * with any kind of lookbehind assertion, such as "\b".
1034 * A #GMatchInfo structure, used to get information on the match, is stored
1035 * in @match_info if not %NULL.
1037 * To retrieve all the non-overlapping matches of the pattern in string you
1038 * can use g_match_info_next().
1040 * <informalexample><programlisting>
1042 * print_uppercase_words (const gchar *string)
1044 * /* Print all uppercase-only words. */
1046 * GMatchInfo *match_info;
1047 * GError *error = NULL;
1049 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1050 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1051 * while (g_match_info_matches (match_info))
1053 * gchar *word = g_match_info_fetch (match_info, 0);
1054 * g_print ("Found: %s\n", word);
1056 * g_match_info_next (match_info, &error);
1058 * g_match_info_free (match_info);
1059 * g_regex_free (regex);
1060 * if (error != NULL)
1062 * g_printerr ("Error while matching: %s\n", error->message);
1063 * g_error_free (error);
1066 * </programlisting></informalexample>
1068 * Returns: %TRUE is the string matched, %FALSE otherwise
1073 g_regex_match_full (const GRegex *regex,
1074 const gchar *string,
1076 gint start_position,
1077 GRegexMatchFlags match_options,
1078 GMatchInfo **match_info,
1084 g_return_val_if_fail (regex != NULL, FALSE);
1085 g_return_val_if_fail (string != NULL, FALSE);
1086 g_return_val_if_fail (start_position >= 0, FALSE);
1087 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1088 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1090 info = match_info_new (regex, string, string_len, start_position,
1091 match_options, FALSE);
1092 match_ok = g_match_info_next (info, error);
1093 if (match_info != NULL)
1096 g_match_info_free (info);
1102 * g_regex_match_all:
1103 * @regex: a #GRegex structure from g_regex_new()
1104 * @string: the string to scan for matches
1105 * @match_options: match options
1106 * @match_info: pointer to location where to store the #GMatchInfo, or
1107 * %NULL if you do not nedd it
1109 * Using the standard algorithm for regular expression matching only the
1110 * longest match in the string is retrieved. This function uses a
1111 * different algorithm so it can retrieve all the possible matches.
1112 * For more documentation see g_regex_match_all_full().
1114 * A #GMatchInfo structure, used to get information on the match, is stored
1115 * in @match_info if not %NULL.
1117 * Returns: %TRUE is the string matched, %FALSE otherwise
1122 g_regex_match_all (const GRegex *regex,
1123 const gchar *string,
1124 GRegexMatchFlags match_options,
1125 GMatchInfo **match_info)
1127 return g_regex_match_all_full (regex, string, -1, 0, match_options,
1132 * g_regex_match_all_full:
1133 * @regex: a #GRegex structure from g_regex_new()
1134 * @string: the string to scan for matches
1135 * @string_len: the length of @string, or -1 if @string is nul-terminated
1136 * @start_position: starting index of the string to match
1137 * @match_options: match options
1138 * @match_info: pointer to location where to store the #GMatchInfo, or
1139 * %NULL if you do not nedd it
1140 * @error: location to store the error occuring, or %NULL to ignore errors
1142 * Using the standard algorithm for regular expression matching only the
1143 * longest match in the string is retrieved, it is not possibile to obtain
1144 * all the available matches. For instance matching
1145 * "<a> <b> <c>" against the pattern "<.*>" you get
1146 * "<a> <b> <c>".
1148 * This function uses a different algorithm (called DFA, i.e. deterministic
1149 * finite automaton), so it can retrieve all the possible matches, all
1150 * starting at the same point in the string. For instance matching
1151 * "<a> <b> <c>" against the pattern "<.*>" you
1152 * would obtain three matches: "<a> <b> <c>",
1153 * "<a> <b>" and "<a>".
1155 * The number of matched strings is retrieved using
1156 * g_match_info_get_match_count().
1157 * To obtain the matched strings and their position you can use,
1158 * respectively, g_match_info_fetch() and g_match_info_fetch_pos(). Note that
1159 * the strings are returned in reverse order of length; that is, the longest
1160 * matching string is given first.
1162 * Note that the DFA algorithm is slower than the standard one and it is not
1163 * able to capture substrings, so backreferences do not work.
1165 * Setting @start_position differs from just passing over a shortened string
1166 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1167 * with any kind of lookbehind assertion, such as "\b".
1169 * A #GMatchInfo structure, used to get information on the match, is stored
1170 * in @match_info if not %NULL.
1172 * Returns: %TRUE is the string matched, %FALSE otherwise
1177 g_regex_match_all_full (const GRegex *regex,
1178 const gchar *string,
1180 gint start_position,
1181 GRegexMatchFlags match_options,
1182 GMatchInfo **match_info,
1188 g_return_val_if_fail (regex != NULL, FALSE);
1189 g_return_val_if_fail (string != NULL, FALSE);
1190 g_return_val_if_fail (start_position >= 0, FALSE);
1191 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1192 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1194 info = match_info_new (regex, string, string_len, start_position,
1195 match_options, TRUE);
1201 info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1202 info->string, info->string_len,
1204 regex->match_opts | match_options,
1205 info->offsets, info->n_offsets,
1206 info->workspace, info->n_workspace);
1207 if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1209 /* info->workspace is too small. */
1210 info->n_workspace *= 2;
1211 info->workspace = g_realloc (info->workspace,
1212 info->n_workspace * sizeof (gint));
1215 else if (info->matches == 0)
1217 /* info->offsets is too small. */
1218 info->n_offsets *= 2;
1219 info->offsets = g_realloc (info->offsets,
1220 info->n_offsets * sizeof (gint));
1223 else if (IS_PCRE_ERROR (info->matches))
1225 g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1226 _("Error while matching regular expression %s: %s"),
1227 regex->pattern, match_error (info->matches));
1231 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1234 if (match_info != NULL)
1237 g_match_info_free (info);
1239 return info->matches >= 0;
1243 * g_regex_get_string_number:
1244 * @regex: #GRegex structure
1245 * @name: name of the subexpression
1247 * Retrieves the number of the subexpression named @name.
1249 * Returns: The number of the subexpression or -1 if @name does not exists
1254 g_regex_get_string_number (const GRegex *regex,
1259 g_return_val_if_fail (regex != NULL, -1);
1260 g_return_val_if_fail (name != NULL, -1);
1262 num = pcre_get_stringnumber (regex->pcre_re, name);
1263 if (num == PCRE_ERROR_NOSUBSTRING)
1270 * g_regex_split_simple:
1271 * @pattern: the regular expression
1272 * @string: the string to scan for matches
1273 * @compile_options: compile options for the regular expression
1274 * @match_options: match options
1276 * Breaks the string on the pattern, and returns an array of the tokens.
1277 * If the pattern contains capturing parentheses, then the text for each
1278 * of the substrings will also be returned. If the pattern does not match
1279 * anywhere in the string, then the whole string is returned as the first
1282 * This function is equivalent to g_regex_split() but it does not
1283 * require to compile the pattern with g_regex_new(), avoiding some
1284 * lines of code when you need just to do a split without extracting
1285 * substrings, capture counts, and so on.
1287 * If this function is to be called on the same @pattern more than
1288 * once, it's more efficient to compile the pattern once with
1289 * g_regex_new() and then use g_regex_split().
1291 * As a special case, the result of splitting the empty string "" is an
1292 * empty vector, not a vector containing a single string. The reason for
1293 * this special case is that being able to represent a empty vector is
1294 * typically more useful than consistent handling of empty elements. If
1295 * you do need to represent empty elements, you'll need to check for the
1296 * empty string before calling this function.
1298 * A pattern that can match empty strings splits @string into separate
1299 * characters wherever it matches the empty string between characters.
1300 * For example splitting "ab c" using as a separator "\s*", you will get
1303 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1308 g_regex_split_simple (const gchar *pattern,
1309 const gchar *string,
1310 GRegexCompileFlags compile_options,
1311 GRegexMatchFlags match_options)
1316 regex = g_regex_new (pattern, compile_options, 0, NULL);
1319 result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1320 g_regex_free (regex);
1326 * @regex: a #GRegex structure
1327 * @string: the string to split with the pattern
1328 * @match_options: match time option flags
1330 * Breaks the string on the pattern, and returns an array of the tokens.
1331 * If the pattern contains capturing parentheses, then the text for each
1332 * of the substrings will also be returned. If the pattern does not match
1333 * anywhere in the string, then the whole string is returned as the first
1336 * As a special case, the result of splitting the empty string "" is an
1337 * empty vector, not a vector containing a single string. The reason for
1338 * this special case is that being able to represent a empty vector is
1339 * typically more useful than consistent handling of empty elements. If
1340 * you do need to represent empty elements, you'll need to check for the
1341 * empty string before calling this function.
1343 * A pattern that can match empty strings splits @string into separate
1344 * characters wherever it matches the empty string between characters.
1345 * For example splitting "ab c" using as a separator "\s*", you will get
1348 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1353 g_regex_split (const GRegex *regex,
1354 const gchar *string,
1355 GRegexMatchFlags match_options)
1357 return g_regex_split_full (regex, string, -1, 0,
1358 match_options, 0, NULL);
1362 * g_regex_split_full:
1363 * @regex: a #GRegex structure
1364 * @string: the string to split with the pattern
1365 * @string_len: the length of @string, or -1 if @string is nul-terminated
1366 * @start_position: starting index of the string to match
1367 * @match_options: match time option flags
1368 * @max_tokens: the maximum number of tokens to split @string into. If this
1369 * is less than 1, the string is split completely
1370 * @error: return location for a #GError
1372 * Breaks the string on the pattern, and returns an array of the tokens.
1373 * If the pattern contains capturing parentheses, then the text for each
1374 * of the substrings will also be returned. If the pattern does not match
1375 * anywhere in the string, then the whole string is returned as the first
1378 * As a special case, the result of splitting the empty string "" is an
1379 * empty vector, not a vector containing a single string. The reason for
1380 * this special case is that being able to represent a empty vector is
1381 * typically more useful than consistent handling of empty elements. If
1382 * you do need to represent empty elements, you'll need to check for the
1383 * empty string before calling this function.
1385 * A pattern that can match empty strings splits @string into separate
1386 * characters wherever it matches the empty string between characters.
1387 * For example splitting "ab c" using as a separator "\s*", you will get
1390 * Setting @start_position differs from just passing over a shortened string
1391 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1392 * with any kind of lookbehind assertion, such as "\b".
1394 * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1399 g_regex_split_full (const GRegex *regex,
1400 const gchar *string,
1402 gint start_position,
1403 GRegexMatchFlags match_options,
1407 GError *tmp_error = NULL;
1408 GMatchInfo *match_info;
1413 /* position of the last separator. */
1414 gint last_separator_end;
1415 /* was the last match 0 bytes long? */
1416 gboolean last_match_is_empty;
1417 /* the returned array of char **s */
1418 gchar **string_list;
1420 g_return_val_if_fail (regex != NULL, NULL);
1421 g_return_val_if_fail (string != NULL, NULL);
1422 g_return_val_if_fail (start_position >= 0, NULL);
1423 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1424 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1426 if (max_tokens <= 0)
1427 max_tokens = G_MAXINT;
1430 string_len = strlen (string);
1432 /* zero-length string */
1433 if (string_len - start_position == 0)
1434 return g_new0 (gchar *, 1);
1436 if (max_tokens == 1)
1438 string_list = g_new0 (gchar *, 2);
1439 string_list[0] = g_strndup (&string[start_position],
1440 string_len - start_position);
1446 last_separator_end = start_position;
1447 last_match_is_empty = FALSE;
1449 match_ok = g_regex_match_full (regex, string, string_len, start_position,
1450 match_options, &match_info, &tmp_error);
1451 while (tmp_error == NULL)
1455 last_match_is_empty =
1456 (match_info->offsets[0] == match_info->offsets[1]);
1458 /* we need to skip empty separators at the same position of the end
1459 * of another separator. e.g. the string is "a b" and the separator
1460 * is " *", so from 1 to 2 we have a match and at position 2 we have
1461 * an empty match. */
1462 if (last_separator_end != match_info->offsets[1])
1467 token = g_strndup (string + last_separator_end,
1468 match_info->offsets[0] - last_separator_end);
1469 list = g_list_prepend (list, token);
1472 /* if there were substrings, these need to be added to
1474 match_count = g_match_info_get_match_count (match_info);
1475 if (match_count > 1)
1477 for (i = 1; i < match_count; i++)
1478 list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1484 /* if there was no match, copy to end of string. */
1485 if (!last_match_is_empty)
1487 gchar *token = g_strndup (string + last_separator_end,
1488 match_info->string_len - last_separator_end);
1489 list = g_list_prepend (list, token);
1491 /* no more tokens, end the loop. */
1495 /* -1 to leave room for the last part. */
1496 if (token_count >= max_tokens - 1)
1498 /* we have reached the maximum number of tokens, so we copy
1499 * the remaining part of the string. */
1500 if (last_match_is_empty)
1502 /* the last match was empty, so we have moved one char
1503 * after the real position to avoid empty matches at the
1505 match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1507 /* the if is needed in the case we have terminated the available
1508 * tokens, but we are at the end of the string, so there are no
1509 * characters left to copy. */
1510 if (string_len > match_info->pos)
1512 gchar *token = g_strndup (string + match_info->pos,
1513 string_len - match_info->pos);
1514 list = g_list_prepend (list, token);
1520 last_separator_end = match_info->pos;
1521 if (last_match_is_empty)
1522 /* if the last match was empty, g_match_info_next() has moved
1523 * forward to avoid infinite loops, but we still need to copy that
1525 last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1527 match_ok = g_match_info_next (match_info, &tmp_error);
1529 g_match_info_free (match_info);
1530 if (tmp_error != NULL)
1532 g_propagate_error (error, tmp_error);
1533 g_list_foreach (list, (GFunc)g_free, NULL);
1535 match_info->pos = -1;
1539 string_list = g_new (gchar *, g_list_length (list) + 1);
1541 for (last = g_list_last (list); last; last = g_list_previous (last))
1542 string_list[i++] = last->data;
1552 REPL_TYPE_CHARACTER,
1553 REPL_TYPE_SYMBOLIC_REFERENCE,
1554 REPL_TYPE_NUMERIC_REFERENCE,
1555 REPL_TYPE_CHANGE_CASE
1560 CHANGE_CASE_NONE = 1 << 0,
1561 CHANGE_CASE_UPPER = 1 << 1,
1562 CHANGE_CASE_LOWER = 1 << 2,
1563 CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1564 CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1565 CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1566 CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1567 CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1570 struct _InterpolationData
1576 ChangeCase change_case;
1580 free_interpolation_data (InterpolationData *data)
1582 g_free (data->text);
1586 static const gchar *
1587 expand_escape (const gchar *replacement,
1589 InterpolationData *data,
1594 const gchar *error_detail;
1596 GError *tmp_error = NULL;
1604 data->type = REPL_TYPE_CHARACTER;
1609 data->type = REPL_TYPE_CHARACTER;
1614 data->type = REPL_TYPE_CHARACTER;
1619 data->type = REPL_TYPE_CHARACTER;
1624 data->type = REPL_TYPE_CHARACTER;
1629 data->type = REPL_TYPE_CHARACTER;
1634 data->type = REPL_TYPE_CHARACTER;
1639 data->type = REPL_TYPE_CHARACTER;
1649 h = g_ascii_xdigit_value (*p);
1652 error_detail = _("hexadecimal digit or '}' expected");
1663 for (i = 0; i < 2; i++)
1665 h = g_ascii_xdigit_value (*p);
1668 error_detail = _("hexadecimal digit expected");
1675 data->type = REPL_TYPE_STRING;
1676 data->text = g_new0 (gchar, 8);
1677 g_unichar_to_utf8 (x, data->text);
1681 data->type = REPL_TYPE_CHANGE_CASE;
1682 data->change_case = CHANGE_CASE_LOWER_SINGLE;
1686 data->type = REPL_TYPE_CHANGE_CASE;
1687 data->change_case = CHANGE_CASE_UPPER_SINGLE;
1691 data->type = REPL_TYPE_CHANGE_CASE;
1692 data->change_case = CHANGE_CASE_LOWER;
1696 data->type = REPL_TYPE_CHANGE_CASE;
1697 data->change_case = CHANGE_CASE_UPPER;
1701 data->type = REPL_TYPE_CHANGE_CASE;
1702 data->change_case = CHANGE_CASE_NONE;
1708 error_detail = _("missing '<' in symbolic reference");
1717 error_detail = _("unfinished symbolic reference");
1724 error_detail = _("zero-length symbolic reference");
1727 if (g_ascii_isdigit (*q))
1732 h = g_ascii_digit_value (*q);
1735 error_detail = _("digit expected");
1744 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1751 if (!g_ascii_isalnum (*r))
1753 error_detail = _("illegal symbolic reference");
1760 data->text = g_strndup (q, p - q);
1761 data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1766 /* if \0 is followed by a number is an octal number representing a
1767 * character, else it is a numeric reference. */
1768 if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1771 p = g_utf8_next_char (p);
1784 for (i = 0; i < 3; i++)
1786 h = g_ascii_digit_value (*p);
1796 if (i == 2 && base == 10)
1802 if (base == 8 || i == 3)
1804 data->type = REPL_TYPE_STRING;
1805 data->text = g_new0 (gchar, 8);
1806 g_unichar_to_utf8 (x, data->text);
1810 data->type = REPL_TYPE_NUMERIC_REFERENCE;
1815 error_detail = _("stray final '\\'");
1819 error_detail = _("unknown escape sequence");
1826 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1827 tmp_error = g_error_new (G_REGEX_ERROR,
1828 G_REGEX_ERROR_REPLACE,
1829 _("Error while parsing replacement "
1830 "text \"%s\" at char %lu: %s"),
1832 (gulong)(p - replacement),
1834 g_propagate_error (error, tmp_error);
1840 split_replacement (const gchar *replacement,
1844 InterpolationData *data;
1845 const gchar *p, *start;
1847 start = p = replacement;
1852 data = g_new0 (InterpolationData, 1);
1853 start = p = expand_escape (replacement, p, data, error);
1856 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1858 free_interpolation_data (data);
1862 list = g_list_prepend (list, data);
1867 if (*p == '\\' || *p == '\0')
1871 data = g_new0 (InterpolationData, 1);
1872 data->text = g_strndup (start, p - start);
1873 data->type = REPL_TYPE_STRING;
1874 list = g_list_prepend (list, data);
1880 return g_list_reverse (list);
1883 /* Change the case of c based on change_case. */
1884 #define CHANGE_CASE(c, change_case) \
1885 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
1886 g_unichar_tolower (c) : \
1887 g_unichar_toupper (c))
1890 string_append (GString *string,
1892 ChangeCase *change_case)
1896 if (text[0] == '\0')
1899 if (*change_case == CHANGE_CASE_NONE)
1901 g_string_append (string, text);
1903 else if (*change_case & CHANGE_CASE_SINGLE_MASK)
1905 c = g_utf8_get_char (text);
1906 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
1907 g_string_append (string, g_utf8_next_char (text));
1908 *change_case = CHANGE_CASE_NONE;
1912 while (*text != '\0')
1914 c = g_utf8_get_char (text);
1915 g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
1916 text = g_utf8_next_char (text);
1922 interpolate_replacement (const GRegex *regex,
1923 const GMatchInfo *match_info,
1924 const gchar *string,
1929 InterpolationData *idata;
1931 ChangeCase change_case = CHANGE_CASE_NONE;
1933 for (list = data; list; list = list->next)
1936 switch (idata->type)
1938 case REPL_TYPE_STRING:
1939 string_append (result, idata->text, &change_case);
1941 case REPL_TYPE_CHARACTER:
1942 g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
1943 if (change_case & CHANGE_CASE_SINGLE_MASK)
1944 change_case = CHANGE_CASE_NONE;
1946 case REPL_TYPE_NUMERIC_REFERENCE:
1947 match = g_match_info_fetch (match_info, idata->num);
1950 string_append (result, match, &change_case);
1954 case REPL_TYPE_SYMBOLIC_REFERENCE:
1955 match = g_match_info_fetch_named (match_info, idata->text);
1958 string_append (result, match, &change_case);
1962 case REPL_TYPE_CHANGE_CASE:
1963 change_case = idata->change_case;
1973 * @regex: a #GRegex structure
1974 * @string: the string to perform matches against
1975 * @string_len: the length of @string, or -1 if @string is nul-terminated
1976 * @start_position: starting index of the string to match
1977 * @replacement: text to replace each match with
1978 * @match_options: options for the match
1979 * @error: location to store the error occuring, or %NULL to ignore errors
1981 * Replaces all occurances of the pattern in @regex with the
1982 * replacement text. Backreferences of the form '\number' or '\g<number>'
1983 * in the replacement text are interpolated by the number-th captured
1984 * subexpression of the match, '\g<name>' refers to the captured subexpression
1985 * with the given name. '\0' refers to the complete match, but '\0' followed
1986 * by a number is the octal representation of a character. To include a
1987 * literal '\' in the replacement, write '\\'.
1988 * There are also escapes that changes the case of the following text:
1991 * <varlistentry><term>\l</term>
1993 * <para>Convert to lower case the next character</para>
1996 * <varlistentry><term>\u</term>
1998 * <para>Convert to upper case the next character</para>
2001 * <varlistentry><term>\L</term>
2003 * <para>Convert to lower case till \E</para>
2006 * <varlistentry><term>\U</term>
2008 * <para>Convert to upper case till \E</para>
2011 * <varlistentry><term>\E</term>
2013 * <para>End case modification</para>
2018 * If you do not need to use backreferences use g_regex_replace_literal().
2020 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2021 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2022 * you can use g_regex_replace_literal().
2024 * Setting @start_position differs from just passing over a shortened string
2025 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2026 * with any kind of lookbehind assertion, such as "\b".
2028 * Returns: a newly allocated string containing the replacements
2033 g_regex_replace (const GRegex *regex,
2034 const gchar *string,
2036 gint start_position,
2037 const gchar *replacement,
2038 GRegexMatchFlags match_options,
2043 GError *tmp_error = NULL;
2045 g_return_val_if_fail (regex != NULL, NULL);
2046 g_return_val_if_fail (string != NULL, NULL);
2047 g_return_val_if_fail (start_position >= 0, NULL);
2048 g_return_val_if_fail (replacement != NULL, NULL);
2049 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2050 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2052 list = split_replacement (replacement, &tmp_error);
2053 if (tmp_error != NULL)
2055 g_propagate_error (error, tmp_error);
2059 result = g_regex_replace_eval (regex,
2060 string, string_len, start_position,
2062 interpolate_replacement,
2065 if (tmp_error != NULL)
2066 g_propagate_error (error, tmp_error);
2068 g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2075 literal_replacement (const GRegex *regex,
2076 const GMatchInfo *match_info,
2077 const gchar *string,
2081 g_string_append (result, data);
2086 * g_regex_replace_literal:
2087 * @regex: a #GRegex structure
2088 * @string: the string to perform matches against
2089 * @string_len: the length of @string, or -1 if @string is nul-terminated
2090 * @start_position: starting index of the string to match
2091 * @replacement: text to replace each match with
2092 * @match_options: options for the match
2093 * @error: location to store the error occuring, or %NULL to ignore errors
2095 * Replaces all occurances of the pattern in @regex with the
2096 * replacement text. @replacement is replaced literally, to
2097 * include backreferences use g_regex_replace().
2099 * Setting @start_position differs from just passing over a shortened string
2100 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2101 * with any kind of lookbehind assertion, such as "\b".
2103 * Returns: a newly allocated string containing the replacements
2108 g_regex_replace_literal (const GRegex *regex,
2109 const gchar *string,
2111 gint start_position,
2112 const gchar *replacement,
2113 GRegexMatchFlags match_options,
2116 g_return_val_if_fail (replacement != NULL, NULL);
2117 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2119 return g_regex_replace_eval (regex,
2120 string, string_len, start_position,
2122 literal_replacement,
2123 (gpointer)replacement,
2128 * g_regex_replace_eval:
2129 * @regex: a #GRegex structure from g_regex_new()
2130 * @string: string to perform matches against
2131 * @string_len: the length of @string, or -1 if @string is nul-terminated
2132 * @start_position: starting index of the string to match
2133 * @match_options: options for the match
2134 * @eval: a function to call for each match
2135 * @user_data: user data to pass to the function
2136 * @error: location to store the error occuring, or %NULL to ignore errors
2138 * Replaces occurances of the pattern in regex with the output of @eval
2139 * for that occurance.
2141 * Setting @start_position differs from just passing over a shortened string
2142 * and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2143 * with any kind of lookbehind assertion, such as "\b".
2145 * Returns: a newly allocated string containing the replacements
2150 g_regex_replace_eval (const GRegex *regex,
2151 const gchar *string,
2153 gint start_position,
2154 GRegexMatchFlags match_options,
2155 GRegexEvalCallback eval,
2159 GMatchInfo *match_info;
2162 gboolean done = FALSE;
2163 GError *tmp_error = NULL;
2165 g_return_val_if_fail (regex != NULL, NULL);
2166 g_return_val_if_fail (string != NULL, NULL);
2167 g_return_val_if_fail (start_position >= 0, NULL);
2168 g_return_val_if_fail (eval != NULL, NULL);
2169 g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2172 string_len = strlen (string);
2174 result = g_string_sized_new (string_len);
2176 /* run down the string making matches. */
2177 g_regex_match_full (regex, string, string_len, start_position,
2178 match_options, &match_info, &tmp_error);
2179 while (!done && g_match_info_matches (match_info))
2181 g_string_append_len (result,
2183 match_info->offsets[0] - str_pos);
2184 done = (*eval) (regex, match_info, string, result, user_data);
2185 str_pos = match_info->offsets[1];
2186 g_match_info_next (match_info, &tmp_error);
2188 g_match_info_free (match_info);
2189 if (tmp_error != NULL)
2191 g_propagate_error (error, tmp_error);
2192 g_string_free (result, TRUE);
2196 g_string_append_len (result, string + str_pos, string_len - str_pos);
2197 return g_string_free (result, FALSE);
2201 * g_regex_escape_string:
2202 * @string: the string to escape
2203 * @length: the length of @string, or -1 if @string is nul-terminated
2205 * Escapes the special characters used for regular expressions in @string,
2206 * for instance "a.b*c" becomes "a\.b\*c". This function is useful to
2207 * dynamically generate regular expressions.
2209 * @string can contain nul characters that are replaced with "\0", in this
2210 * case remember to specify the correct length of @string in @length.
2212 * Returns: a newly-allocated escaped string
2217 g_regex_escape_string (const gchar *string,
2221 const char *p, *piece_start, *end;
2223 g_return_val_if_fail (string != NULL, NULL);
2226 length = strlen (string);
2228 end = string + length;
2229 p = piece_start = string;
2230 escaped = g_string_sized_new (length + 1);
2251 if (p != piece_start)
2252 /* copy the previous piece. */
2253 g_string_append_len (escaped, piece_start, p - piece_start);
2254 g_string_append_c (escaped, '\\');
2256 g_string_append_c (escaped, '0');
2258 g_string_append_c (escaped, *p);
2262 p = g_utf8_next_char (p);
2267 if (piece_start < end)
2268 g_string_append_len (escaped, piece_start, end - piece_start);
2270 return g_string_free (escaped, FALSE);
2273 #define __G_REGEX_C__
2274 #include "galiasdef.c"