fixed g_regex_fetch_named* for cases when (?J) is used inside a pattern
[platform/upstream/glib.git] / glib / gregex.c
1 /* GRegex -- regular expression API wrapper around PCRE.
2  *
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>
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include <config.h>
23
24 #include "gregex.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <string.h>
29
30 #ifdef USE_SYSTEM_PCRE
31 #include <pcre.h>
32 #else
33 #include "pcre/pcre.h"
34 #endif
35
36 #include "galias.h"
37
38 /* Mask of all the possible values for GRegexCompileFlags. */
39 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS          | \
40                               G_REGEX_MULTILINE         | \
41                               G_REGEX_DOTALL            | \
42                               G_REGEX_EXTENDED          | \
43                               G_REGEX_ANCHORED          | \
44                               G_REGEX_DOLLAR_ENDONLY    | \
45                               G_REGEX_UNGREEDY          | \
46                               G_REGEX_RAW               | \
47                               G_REGEX_NO_AUTO_CAPTURE   | \
48                               G_REGEX_OPTIMIZE          | \
49                               G_REGEX_DUPNAMES          | \
50                               G_REGEX_NEWLINE_CR        | \
51                               G_REGEX_NEWLINE_LF        | \
52                               G_REGEX_NEWLINE_CRLF)
53
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)
64
65 /* if the string is in UTF-8 use g_utf8_ functions, else use
66  * use just +/- 1. */
67 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
68                                 g_utf8_next_char (s) : \
69                                 ((s) + 1))
70 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
71                                 g_utf8_prev_char (s) : \
72                                 ((s) - 1))
73
74 struct _GMatchInfo
75 {
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 */
86 };
87
88 struct _GRegex
89 {
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 */
96 };
97
98 /* TRUE if ret is an error code, FALSE otherwise. */
99 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
100
101 typedef struct _InterpolationData InterpolationData;
102 static gboolean  interpolation_list_needs_match (GList *list);
103 static gboolean  interpolate_replacement        (const GMatchInfo *match_info,
104                                                  GString *result,
105                                                  gpointer data);
106 static GList    *split_replacement              (const gchar *replacement,
107                                                  GError **error);
108 static void      free_interpolation_data        (InterpolationData *data);
109
110
111 static const gchar *
112 match_error (gint errcode)
113 {
114   switch (errcode)
115     {
116     case PCRE_ERROR_NOMATCH:
117       /* not an error */
118       break;
119     case PCRE_ERROR_NULL:
120       /* NULL argument, this should not happen in GRegex */
121       g_warning ("A NULL argument was passed to PCRE");
122       break;
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() */
133       break;
134     case PCRE_ERROR_MATCHLIMIT:
135       return _("backtracking limit reached");
136     case PCRE_ERROR_CALLOUT:
137       /* callouts are not implemented */
138       break;
139     case PCRE_ERROR_BADUTF8:
140     case PCRE_ERROR_BADUTF8_OFFSET:
141       /* we do not check if strings are valid */
142       break;
143     case PCRE_ERROR_PARTIAL:
144       /* not an error */
145       break;
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");
153       break;
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 */
160       break;
161     case PCRE_ERROR_DFA_WSSIZE:
162       /* handled expanding the workspace */
163       break;
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");
171     default:
172       break;
173     }
174   return _("unknown error");
175 }
176
177
178 /* GMatchInfo */
179
180 static GMatchInfo *
181 match_info_new (const GRegex *regex,
182                 const gchar  *string,
183                 gint          string_len,
184                 gint          start_position,
185                 gint          match_options,
186                 gboolean      is_dfa)
187 {
188   GMatchInfo *match_info;
189
190   if (string_len < 0)
191     string_len = strlen (string);
192
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;
200
201   if (is_dfa)
202     {
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);
208     }
209   else
210     {
211       gint capture_count;
212       pcre_fullinfo (regex->pcre_re, regex->extra,
213                      PCRE_INFO_CAPTURECOUNT, &capture_count);
214       match_info->n_offsets = (capture_count + 1) * 3;
215     }
216   match_info->offsets = g_new0 (gint, match_info->n_offsets);
217
218   return match_info;
219 }
220
221 /**
222  * g_match_info_get_regex:
223  * @match_info: a #GMatchInfo
224  *
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.
228  *
229  * Returns: #GRegex object used in @match_info
230  *
231  * Since: 2.14
232  */
233 GRegex *
234 g_match_info_get_regex (const GMatchInfo *match_info)
235 {
236   g_return_val_if_fail (match_info != NULL, NULL);
237   return match_info->regex;
238 }
239
240 /**
241  * g_match_info_get_string:
242  * @match_info: a #GMatchInfo
243  *
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.
247  *
248  * Returns: the string searched with @match_info
249  *
250  * Since: 2.14
251  */
252 const gchar *
253 g_match_info_get_string (const GMatchInfo *match_info)
254 {
255   g_return_val_if_fail (match_info != NULL, NULL);
256   return match_info->string;
257 }
258
259 /**
260  * g_match_info_free:
261  * @match_info: a #GMatchInfo
262  *
263  * Frees all the memory associated with the #GMatchInfo structure.
264  *
265  * Since: 2.14
266  */
267 void
268 g_match_info_free (GMatchInfo *match_info)
269 {
270   if (match_info)
271     {
272       g_regex_unref (match_info->regex);
273       g_free (match_info->offsets);
274       g_free (match_info->workspace);
275       g_free (match_info);
276     }
277 }
278
279 /**
280  * g_match_info_next:
281  * @match_info: a #GMatchInfo structure
282  * @error: location to store the error occuring, or NULL to ignore errors
283  *
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
286  * @match_info.
287  *
288  * The match is done on the string passed to the match function, so you
289  * cannot free it before calling this function.
290  *
291  * Returns: %TRUE is the string matched, %FALSE otherwise
292  *
293  * Since: 2.14
294  */
295 gboolean
296 g_match_info_next (GMatchInfo  *match_info,
297                    GError     **error)
298 {
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);
302
303   match_info->matches = pcre_exec (match_info->regex->pcre_re,
304                                    match_info->regex->extra,
305                                    match_info->string,
306                                    match_info->string_len,
307                                    match_info->pos,
308                                    match_info->regex->match_opts |
309                                    match_info->match_opts,
310                                    match_info->offsets,
311                                    match_info->n_offsets);
312   if (IS_PCRE_ERROR (match_info->matches))
313     {
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));
317       return FALSE;
318     }
319
320   /* avoid infinite loops if the pattern is an empty string or something
321    * equivalent */
322   if (match_info->pos == match_info->offsets[1])
323     {
324       if (match_info->pos > match_info->string_len)
325         {
326           /* we have reached the end of the string */
327           match_info->pos = -1;
328           match_info->matches = PCRE_ERROR_NOMATCH;
329           return FALSE;
330         }
331       match_info->pos = NEXT_CHAR (match_info->regex,
332                                    &match_info->string[match_info->pos]) -
333                                    match_info->string;
334     }
335   else
336     {
337       match_info->pos = match_info->offsets[1];
338     }
339
340   return match_info->matches >= 0;
341 }
342
343 /**
344  * g_match_info_matches:
345  * @match_info: a #GMatchInfo structure
346  *
347  * Returns: %TRUE if the previous match operation succeeded, %FALSE
348  * otherwise
349  *
350  * Since: 2.14
351  */
352 gboolean
353 g_match_info_matches (const GMatchInfo *match_info)
354 {
355   g_return_val_if_fail (match_info != NULL, FALSE);
356
357   return match_info->matches >= 0;
358 }
359
360 /**
361  * g_match_info_get_match_count:
362  * @match_info: a #GMatchInfo structure
363  *
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.
367  *
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.
372  *
373  * Returns:  Number of matched substrings, or -1 if an error occurred
374  *
375  * Since: 2.14
376  */
377 gint
378 g_match_info_get_match_count (const GMatchInfo *match_info)
379 {
380   g_return_val_if_fail (match_info, -1);
381
382   if (match_info->matches == PCRE_ERROR_NOMATCH)
383     /* no match */
384     return 0;
385   else if (match_info->matches < PCRE_ERROR_NOMATCH)
386     /* error */
387     return -1;
388   else
389     /* match */
390     return match_info->matches;
391 }
392
393 /**
394  * g_match_info_is_partial_match:
395  * @match_info: a #GMatchInfo structure
396  *
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.
401  *
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.
409  *
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().
416  *
417  * When using partial matching you cannot use g_match_info_fetch*().
418  *
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.
428  *
429  * Returns: %TRUE if the match was partial, %FALSE otherwise
430  *
431  * Since: 2.14
432  */
433 gboolean
434 g_match_info_is_partial_match (const GMatchInfo *match_info)
435 {
436   g_return_val_if_fail (match_info != NULL, FALSE);
437
438   return match_info->matches == PCRE_ERROR_PARTIAL;
439 }
440
441 /**
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
446  *
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
450  * g_regex_replace().
451  *
452  * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
453  * passed to g_regex_new().
454  *
455  * The backreferences are extracted from the string passed to the match
456  * function, so you cannot call this function after freeing the string.
457  *
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.
464  *
465  * Returns: the expanded string, or %NULL if an error occurred
466  *
467  * Since: 2.14
468  */
469 gchar *
470 g_match_info_expand_references (const GMatchInfo *match_info, 
471                                 const gchar      *string_to_expand,
472                                 GError          **error)
473 {
474   GString *result;
475   GList *list;
476   GError *tmp_error = NULL;
477
478   g_return_val_if_fail (string_to_expand != NULL, NULL);
479   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
480
481   list = split_replacement (string_to_expand, &tmp_error);
482   if (tmp_error != NULL)
483     {
484       g_propagate_error (error, tmp_error);
485       return NULL;
486     }
487
488   if (!match_info && interpolation_list_needs_match (list))
489     {
490       g_critical ("String '%s' contains references to the match, can't "
491                   "expand references without GMatchInfo object",
492                   string_to_expand);
493       return NULL;
494     }
495
496   result = g_string_sized_new (strlen (string_to_expand));
497   interpolate_replacement (match_info, result, list);
498
499   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
500   g_list_free (list);
501
502   return g_string_free (result, FALSE);
503 }
504
505 /**
506  * g_match_info_fetch:
507  * @match_info: #GMatchInfo structure
508  * @match_num: number of the sub expression
509  *
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,
512  * and so on.
513  *
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
516  * returned.
517  *
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
522  * the longest match.
523  *
524  * The string is fetched from the string passed to the match function,
525  * so you cannot call this function after freeing the string.
526  *
527  * Returns: The matched substring, or %NULL if an error occurred.
528  *          You have to free the string yourself
529  *
530  * Since: 2.14
531  */
532 gchar *
533 g_match_info_fetch (const GMatchInfo *match_info,
534                     gint              match_num)
535 {
536   /* we cannot use pcre_get_substring() because it allocates the
537    * string using pcre_malloc(). */
538   gchar *match = NULL;
539   gint start, end;
540
541   g_return_val_if_fail (match_info != NULL, NULL);
542   g_return_val_if_fail (match_num >= 0, NULL);
543
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))
547     match = NULL;
548   else if (start == -1)
549     match = g_strdup ("");
550   else
551     match = g_strndup (&match_info->string[start], end - start);
552
553   return match;
554 }
555
556 /**
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
562  *
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,
565  * and so on.
566  *
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.
570  *
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
575  * the longest match.
576  *
577  * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
578  *          position cannot be fetched, @start_pos and @end_pos are left
579  *          unchanged.
580  *
581  * Since: 2.14
582  */
583 gboolean
584 g_match_info_fetch_pos (const GMatchInfo *match_info,
585                         gint              match_num,
586                         gint             *start_pos,
587                         gint             *end_pos)
588 {
589   g_return_val_if_fail (match_info != NULL, FALSE);
590   g_return_val_if_fail (match_num >= 0, FALSE);
591  
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)
595     return FALSE;
596
597   if (start_pos != NULL)
598     *start_pos = match_info->offsets[2 * match_num];
599
600   if (end_pos != NULL)
601     *end_pos = match_info->offsets[2 * match_num + 1];
602
603   return TRUE;
604 }
605
606 /*
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.
611  */
612 static gint
613 get_matched_substring_number (const GMatchInfo *match_info,
614                               const gchar      *name)
615 {
616   gint entrysize;
617   gchar *first, *last;
618   guchar *entry;
619
620   /*
621    * FIXME: (?J) may be used inside the pattern as the equivalent of
622    * DUPNAMES compile option. In this case we can't know about it,
623    * and pcre doesn't tell us about it either, it uses private flag
624    * PCRE_JCHANGED for this. So we have to always search string
625    * table, unlike pcre which uses pcre_get_stringnumber() shortcut
626    * when possible. It shouldn't be actually bad since
627    * pcre_get_stringtable_entries() uses binary search; still would 
628    * be better to fix it, to be not worse than pcre.
629    */
630 #if 0
631   if ((match_info->regex->compile_opts & G_REGEX_DUPNAMES) == 0)
632     return pcre_get_stringnumber (match_info->regex->pcre_re, name);
633 #endif
634
635   /* This code is copied from pcre_get.c: get_first_set() */
636   entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re, 
637                                             name,
638                                             &first,
639                                             &last);
640
641   if (entrysize <= 0)
642     return entrysize;
643
644   for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
645     {
646       gint n = (entry[0] << 8) + entry[1];
647       if (match_info->offsets[n*2] >= 0)
648         return n;
649     }
650
651   return (first[0] << 8) + first[1];
652 }
653
654 /**
655  * g_match_info_fetch_named:
656  * @match_info: #GMatchInfo structure
657  * @name: name of the subexpression
658  *
659  * Retrieves the text matching the capturing parentheses named @name.
660  *
661  * If @name is a valid sub pattern name but it didn't match anything (e.g.
662  * sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b") then an empty
663  * string is returned.
664  *
665  * The string is fetched from the string passed to the match function,
666  * so you cannot call this function after freeing the string.
667  *
668  * Returns: The matched substring, or %NULL if an error occurred.
669  *          You have to free the string yourself
670  *
671  * Since: 2.14
672  */
673 gchar *
674 g_match_info_fetch_named (const GMatchInfo *match_info,
675                           const gchar      *name)
676 {
677   /* we cannot use pcre_get_named_substring() because it allocates the
678    * string using pcre_malloc(). */
679   gint num;
680
681   g_return_val_if_fail (match_info != NULL, NULL);
682   g_return_val_if_fail (name != NULL, NULL);
683
684   num = get_matched_substring_number (match_info, name);
685   if (num < 0)
686     return NULL;
687   else
688     return g_match_info_fetch (match_info, num);
689 }
690
691 /**
692  * g_match_info_fetch_named_pos:
693  * @match_info: #GMatchInfo structure
694  * @name: name of the subexpression
695  * @start_pos: pointer to location where to store the start position
696  * @end_pos: pointer to location where to store the end position
697  *
698  * Retrieves the position of the capturing parentheses named @name.
699  *
700  * If @name is a valid sub pattern name but it didn't match anything (e.g.
701  * sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b") then @start_pos and
702  * @end_pos are set to -1 and %TRUE is returned.
703  *
704  * Returns: %TRUE if the position was fetched, %FALSE otherwise. If the
705  *          position cannot be fetched, @start_pos and @end_pos are left
706  *          unchanged.
707  *
708  * Since: 2.14
709  */
710 gboolean
711 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
712                               const gchar      *name,
713                               gint             *start_pos,
714                               gint             *end_pos)
715 {
716   gint num;
717
718   g_return_val_if_fail (match_info != NULL, FALSE);
719   g_return_val_if_fail (name != NULL, FALSE);
720
721   num = get_matched_substring_number (match_info, name);
722   if (num < 0)
723     return FALSE;
724
725   return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
726 }
727
728 /**
729  * g_match_info_fetch_all:
730  * @match_info: a #GMatchInfo structure
731  *
732  * Bundles up pointers to each of the matching substrings from a match
733  * and stores them in an array of gchar pointers. The first element in
734  * the returned array is the match number 0, i.e. the entire matched
735  * text.
736  *
737  * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
738  * "b" against "(a)?b") then an empty string is inserted.
739  *
740  * If the last match was obtained using the DFA algorithm, that is using
741  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
742  * strings are not that matched by sets of parentheses but that of the
743  * matched substring. Substrings are matched in reverse order of length,
744  * so the first one is the longest match.
745  *
746  * The strings are fetched from the string passed to the match function,
747  * so you cannot call this function after freeing the string.
748  *
749  * Returns: a %NULL-terminated array of gchar * pointers. It must be freed
750  *          using g_strfreev(). If the previous match failed %NULL is
751  *          returned.
752  *
753  * Since: 2.14
754  */
755 gchar **
756 g_match_info_fetch_all (const GMatchInfo *match_info)
757 {
758   /* we cannot use pcre_get_substring_list() because the returned value
759    * isn't suitable for g_strfreev(). */
760   gchar **result;
761   gint i;
762
763   g_return_val_if_fail (match_info != NULL, FALSE);
764
765   if (match_info->matches < 0)
766     return NULL;
767
768   result = g_new (gchar *, match_info->matches + 1);
769   for (i = 0; i < match_info->matches; i++)
770     result[i] = g_match_info_fetch (match_info, i);
771   result[i] = NULL;
772
773   return result;
774 }
775
776
777 /* GRegex */
778
779 GQuark
780 g_regex_error_quark (void)
781 {
782   static GQuark error_quark = 0;
783
784   if (error_quark == 0)
785     error_quark = g_quark_from_static_string ("g-regex-error-quark");
786
787   return error_quark;
788 }
789
790 /**
791  * g_regex_ref:
792  * @regex: a #GRegex
793  *
794  * Increases reference count of @regex by 1.
795  *
796  * Returns: @regex
797  *
798  * Since: 2.14
799  */
800 GRegex *
801 g_regex_ref (GRegex *regex)
802 {
803   g_return_val_if_fail (regex != NULL, NULL);
804   g_atomic_int_inc ((gint*) &regex->ref_count);
805   return regex;
806 }
807
808 /**
809  * g_regex_unref:
810  * @regex: a #GRegex
811  *
812  * Decreases reference count of @regex by 1. When reference count drops
813  * to zero, it frees all the memory associated with the regex structure.
814  *
815  * Since: 2.14
816  */
817 void
818 g_regex_unref (GRegex *regex)
819 {
820   g_return_if_fail (regex != NULL);
821
822   if (g_atomic_int_exchange_and_add ((gint *) &regex->ref_count, -1) - 1 == 0)
823     {
824       g_free (regex->pattern);
825       if (regex->pcre_re != NULL)
826         pcre_free (regex->pcre_re);
827       if (regex->extra != NULL)
828         pcre_free (regex->extra);
829       g_free (regex);
830     }
831 }
832
833 /** 
834  * g_regex_new:
835  * @pattern: the regular expression
836  * @compile_options: compile options for the regular expression
837  * @match_options: match options for the regular expression
838  * @error: return location for a #GError
839  * 
840  * Compiles the regular expression to an internal form, and does the initial
841  * setup of the #GRegex structure.  
842  * 
843  * Returns: a #GRegex structure. Call g_regex_unref() when you are done
844  * with it.
845  *
846  * Since: 2.14
847  */
848 GRegex *
849 g_regex_new (const gchar         *pattern, 
850              GRegexCompileFlags   compile_options,
851              GRegexMatchFlags     match_options,
852              GError             **error)
853 {
854   GRegex *regex;
855   pcre *re;
856   const gchar *errmsg;
857   gint erroffset;
858   gboolean optimize = FALSE;
859   static gboolean initialized = FALSE;
860   
861   g_return_val_if_fail (pattern != NULL, NULL);
862   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
863   g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
864   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
865
866   if (!initialized)
867     {
868       gint support;
869       const gchar *msg;
870
871       pcre_config (PCRE_CONFIG_UTF8, &support);
872       if (!support)
873         {
874           msg = N_("PCRE library is compiled without UTF8 support");
875           g_critical (msg);
876           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
877           return NULL;
878         }
879
880       pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
881       if (!support)
882         {
883           msg = N_("PCRE library is compiled without UTF8 properties support");
884           g_critical (msg);
885           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
886           return NULL;
887         }
888
889       initialized = TRUE;
890     }
891
892   /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
893    * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
894   if (compile_options & G_REGEX_OPTIMIZE)
895     optimize = TRUE;
896
897   /* In GRegex the string are, by default, UTF-8 encoded. PCRE
898    * instead uses UTF-8 only if required with PCRE_UTF8. */
899   if (compile_options & G_REGEX_RAW)
900     {
901       /* disable utf-8 */
902       compile_options &= ~G_REGEX_RAW;
903     }
904   else
905     {
906       /* enable utf-8 */
907       compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
908       match_options |= PCRE_NO_UTF8_CHECK;
909     }
910
911   /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
912    * not for the system one. */
913   if (!(compile_options & G_REGEX_NEWLINE_CR) &&
914       !(compile_options & G_REGEX_NEWLINE_LF))
915     {
916       compile_options |= PCRE_NEWLINE_ANY;
917     }
918
919   /* compile the pattern */
920   re = pcre_compile (pattern, compile_options, &errmsg, &erroffset, NULL);
921
922   /* if the compilation failed, set the error member and return 
923    * immediately */
924   if (re == NULL)
925     {
926       GError *tmp_error = g_error_new (G_REGEX_ERROR, 
927                                        G_REGEX_ERROR_COMPILE,
928                                        _("Error while compiling regular "
929                                          "expression %s at char %d: %s"),
930                                        pattern, erroffset, errmsg);
931       g_propagate_error (error, tmp_error);
932
933       return NULL;
934     }
935
936   regex = g_new0 (GRegex, 1);
937   regex->ref_count = 1;
938   regex->pattern = g_strdup (pattern);
939   regex->pcre_re = re;
940   regex->compile_opts = compile_options;
941   regex->match_opts = match_options;
942
943   if (optimize)
944     {
945       regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
946       if (errmsg != NULL)
947         {
948           GError *tmp_error = g_error_new (G_REGEX_ERROR,
949                                            G_REGEX_ERROR_OPTIMIZE, 
950                                            _("Error while optimizing "
951                                              "regular expression %s: %s"),
952                                            regex->pattern,
953                                            errmsg);
954           g_propagate_error (error, tmp_error);
955           return NULL;
956         }
957     }
958
959   return regex;
960 }
961
962 /**
963  * g_regex_get_pattern:
964  * @regex: a #GRegex structure
965  *
966  * Gets the pattern string associated with @regex, i.e. a copy of 
967  * the string passed to g_regex_new().
968  *
969  * Returns: the pattern of @regex
970  *
971  * Since: 2.14
972  */
973 const gchar *
974 g_regex_get_pattern (const GRegex *regex)
975 {
976   g_return_val_if_fail (regex != NULL, NULL);
977
978   return regex->pattern;
979 }
980
981 /**
982  * g_regex_get_max_backref:
983  * @regex: a #GRegex
984  *  
985  * Returns the number of the highest back reference
986  * in the pattern, or 0 if the pattern does not contain
987  * back references.
988  *
989  * Returns: the number of the highest back reference.
990  *
991  * Since: 2.14
992  */
993 gint
994 g_regex_get_max_backref (const GRegex *regex)
995 {
996   gint value;
997
998   pcre_fullinfo (regex->pcre_re, regex->extra,
999                  PCRE_INFO_BACKREFMAX, &value);
1000
1001   return value;
1002 }
1003
1004 /**
1005  * g_regex_get_capture_count:
1006  * @regex: a #GRegex
1007  *
1008  * Returns the number of capturing subpatterns in the pattern.
1009  *
1010  * Returns: the number of capturing subpatterns.
1011  *
1012  * Since: 2.14
1013  */
1014 gint
1015 g_regex_get_capture_count (const GRegex *regex)
1016 {
1017   gint value;
1018
1019   pcre_fullinfo (regex->pcre_re, regex->extra,
1020                  PCRE_INFO_CAPTURECOUNT, &value);
1021
1022   return value;
1023 }
1024
1025 /**
1026  * g_regex_match_simple:
1027  * @pattern: the regular expression
1028  * @string: the string to scan for matches
1029  * @compile_options: compile options for the regular expression
1030  * @match_options: match options
1031  *
1032  * Scans for a match in @string for @pattern.
1033  *
1034  * This function is equivalent to g_regex_match() but it does not
1035  * require to compile the pattern with g_regex_new(), avoiding some
1036  * lines of code when you need just to do a match without extracting
1037  * substrings, capture counts, and so on.
1038  *
1039  * If this function is to be called on the same @pattern more than
1040  * once, it's more efficient to compile the pattern once with
1041  * g_regex_new() and then use g_regex_match().
1042  *
1043  * Returns: %TRUE is the string matched, %FALSE otherwise
1044  *
1045  * Since: 2.14
1046  */
1047 gboolean
1048 g_regex_match_simple (const gchar        *pattern, 
1049                       const gchar        *string, 
1050                       GRegexCompileFlags  compile_options,
1051                       GRegexMatchFlags    match_options)
1052 {
1053   GRegex *regex;
1054   gboolean result;
1055
1056   regex = g_regex_new (pattern, compile_options, 0, NULL);
1057   if (!regex)
1058     return FALSE;
1059   result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1060   g_regex_unref (regex);
1061   return result;
1062 }
1063
1064 /**
1065  * g_regex_match:
1066  * @regex: a #GRegex structure from g_regex_new()
1067  * @string: the string to scan for matches
1068  * @match_options: match options
1069  * @match_info: pointer to location where to store the #GMatchInfo, or
1070  * %NULL if you do not need it
1071  *
1072  * Scans for a match in string for the pattern in @regex. The @match_options
1073  * are combined with the match options specified when the @regex structure
1074  * was created, letting you have more flexibility in reusing #GRegex
1075  * structures.
1076  *
1077  * A #GMatchInfo structure, used to get information on the match, is stored
1078  * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1079  * it is created even if the function returns %FALSE, i.e. you must free it
1080  * regardless if regular expression actually matched.
1081  *
1082  * To retrieve all the non-overlapping matches of the pattern in string you
1083  * can use g_match_info_next().
1084  *
1085  * <informalexample><programlisting>
1086  * static void
1087  * print_uppercase_words (const gchar *string)
1088  * {
1089  *   /&ast; Print all uppercase-only words. &ast;/
1090  *   GRegex *regex;
1091  *   GMatchInfo *match_info;
1092  *   &nbsp;
1093  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1094  *   g_regex_match (regex, string, 0, &match_info);
1095  *   while (g_match_info_matches (match_info))
1096  *     {
1097  *       gchar *word = g_match_info_fetch (match_info, 0);
1098  *       g_print ("Found: %s\n", word);
1099  *       g_free (word);
1100  *       g_match_info_next (match_info, NULL);
1101  *     }
1102  *   g_match_info_free (match_info);
1103  *   g_regex_unref (regex);
1104  * }
1105  * </programlisting></informalexample>
1106  *
1107  * Returns: %TRUE is the string matched, %FALSE otherwise
1108  *
1109  * Since: 2.14
1110  */
1111 gboolean
1112 g_regex_match (const GRegex    *regex, 
1113                const gchar     *string, 
1114                GRegexMatchFlags match_options,
1115                GMatchInfo     **match_info)
1116 {
1117   return g_regex_match_full (regex, string, -1, 0, match_options,
1118                              match_info, NULL);
1119 }
1120
1121 /**
1122  * g_regex_match_full:
1123  * @regex: a #GRegex structure from g_regex_new()
1124  * @string: the string to scan for matches
1125  * @string_len: the length of @string, or -1 if @string is nul-terminated
1126  * @start_position: starting index of the string to match
1127  * @match_options: match options
1128  * @match_info: pointer to location where to store the #GMatchInfo, or
1129  * %NULL if you do not need it
1130  * @error: location to store the error occuring, or %NULL to ignore errors
1131  *
1132  * Scans for a match in string for the pattern in @regex. The @match_options
1133  * are combined with the match options specified when the @regex structure
1134  * was created, letting you have more flexibility in reusing #GRegex
1135  * structures.
1136  *
1137  * Setting @start_position differs from just passing over a shortened string
1138  * and  setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1139  * with any kind of lookbehind assertion, such as "\b".
1140  *
1141  * A #GMatchInfo structure, used to get information on the match, is stored
1142  * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1143  * it is created even if the function returns %FALSE, i.e. you must free it
1144  * regardless if regular expression actually matched.
1145  *
1146  * @string is not copied and is used in #GMatchInfo internally. If you use
1147  * any #GMatchInfo method (except g_match_info_free()) after freeing or
1148  * modifying @string then the behaviour is undefined.
1149  *
1150  * To retrieve all the non-overlapping matches of the pattern in string you
1151  * can use g_match_info_next().
1152  *
1153  * <informalexample><programlisting>
1154  * static void
1155  * print_uppercase_words (const gchar *string)
1156  * {
1157  *   /&ast; Print all uppercase-only words. &ast;/
1158  *   GRegex *regex;
1159  *   GMatchInfo *match_info;
1160  *   GError *error = NULL;
1161  *   &nbsp;
1162  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1163  *   g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1164  *   while (g_match_info_matches (match_info))
1165  *     {
1166  *       gchar *word = g_match_info_fetch (match_info, 0);
1167  *       g_print ("Found: %s\n", word);
1168  *       g_free (word);
1169  *       g_match_info_next (match_info, &error);
1170  *     }
1171  *   g_match_info_free (match_info);
1172  *   g_regex_unref (regex);
1173  *   if (error != NULL)
1174  *     {
1175  *       g_printerr ("Error while matching: %s\n", error->message);
1176  *       g_error_free (error);
1177  *     }
1178  * }
1179  * </programlisting></informalexample>
1180  *
1181  * Returns: %TRUE is the string matched, %FALSE otherwise
1182  *
1183  * Since: 2.14
1184  */
1185 gboolean
1186 g_regex_match_full (const GRegex    *regex,
1187                     const gchar     *string,
1188                     gssize           string_len,
1189                     gint             start_position,
1190                     GRegexMatchFlags match_options,
1191                     GMatchInfo     **match_info,
1192                     GError         **error)
1193 {
1194   GMatchInfo *info;
1195   gboolean match_ok;
1196
1197   g_return_val_if_fail (regex != NULL, FALSE);
1198   g_return_val_if_fail (string != NULL, FALSE);
1199   g_return_val_if_fail (start_position >= 0, FALSE);
1200   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1201   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1202
1203   info = match_info_new (regex, string, string_len, start_position,
1204                          match_options, FALSE);
1205   match_ok = g_match_info_next (info, error);
1206   if (match_info != NULL)
1207     *match_info = info;
1208   else
1209     g_match_info_free (info);
1210
1211   return match_ok;
1212 }
1213
1214 /**
1215  * g_regex_match_all:
1216  * @regex: a #GRegex structure from g_regex_new()
1217  * @string: the string to scan for matches
1218  * @match_options: match options
1219  * @match_info: pointer to location where to store the #GMatchInfo, or
1220  * %NULL if you do not need it
1221  *
1222  * Using the standard algorithm for regular expression matching only the
1223  * longest match in the string is retrieved. This function uses a
1224  * different algorithm so it can retrieve all the possible matches.
1225  * For more documentation see g_regex_match_all_full().
1226  *
1227  * A #GMatchInfo structure, used to get information on the match, is stored
1228  * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1229  * it is created even if the function returns %FALSE, i.e. you must free it
1230  * regardless if regular expression actually matched.
1231  *
1232  * Returns: %TRUE is the string matched, %FALSE otherwise
1233  *
1234  * Since: 2.14
1235  */
1236 gboolean
1237 g_regex_match_all (const GRegex    *regex,
1238                    const gchar     *string,
1239                    GRegexMatchFlags match_options,
1240                    GMatchInfo     **match_info)
1241 {
1242   return g_regex_match_all_full (regex, string, -1, 0, match_options,
1243                                  match_info, NULL);
1244 }
1245
1246 /**
1247  * g_regex_match_all_full:
1248  * @regex: a #GRegex structure from g_regex_new()
1249  * @string: the string to scan for matches
1250  * @string_len: the length of @string, or -1 if @string is nul-terminated
1251  * @start_position: starting index of the string to match
1252  * @match_options: match options
1253  * @match_info: pointer to location where to store the #GMatchInfo, or
1254  * %NULL if you do not need it
1255  * @error: location to store the error occuring, or %NULL to ignore errors
1256  *
1257  * Using the standard algorithm for regular expression matching only the
1258  * longest match in the string is retrieved, it is not possibile to obtain
1259  * all the available matches. For instance matching
1260  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;" you get
1261  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;".
1262  *
1263  * This function uses a different algorithm (called DFA, i.e. deterministic
1264  * finite automaton), so it can retrieve all the possible matches, all
1265  * starting at the same point in the string. For instance matching
1266  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;" you
1267  * would obtain three matches: "&lt;a&gt; &lt;b&gt; &lt;c&gt;",
1268  * "&lt;a&gt; &lt;b&gt;" and "&lt;a&gt;".
1269  *
1270  * The number of matched strings is retrieved using
1271  * g_match_info_get_match_count().
1272  * To obtain the matched strings and their position you can use,
1273  * respectively, g_match_info_fetch() and g_match_info_fetch_pos(). Note that
1274  * the strings are returned in reverse order of length; that is, the longest
1275  * matching string is given first.
1276  *
1277  * Note that the DFA algorithm is slower than the standard one and it is not
1278  * able to capture substrings, so backreferences do not work.
1279  *
1280  * Setting @start_position differs from just passing over a shortened string
1281  * and  setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1282  * with any kind of lookbehind assertion, such as "\b".
1283  *
1284  * A #GMatchInfo structure, used to get information on the match, is stored
1285  * in @match_info if not %NULL. Note that if @match_info is not %NULL then
1286  * it is created even if the function returns %FALSE, i.e. you must free it
1287  * regardless if regular expression actually matched.
1288  *
1289  * Returns: %TRUE is the string matched, %FALSE otherwise
1290  *
1291  * Since: 2.14
1292  */
1293 gboolean
1294 g_regex_match_all_full (const GRegex    *regex,
1295                         const gchar     *string,
1296                         gssize           string_len,
1297                         gint             start_position,
1298                         GRegexMatchFlags match_options,
1299                         GMatchInfo     **match_info,
1300                         GError         **error)
1301 {
1302   GMatchInfo *info;
1303   gboolean done;
1304
1305   g_return_val_if_fail (regex != NULL, FALSE);
1306   g_return_val_if_fail (string != NULL, FALSE);
1307   g_return_val_if_fail (start_position >= 0, FALSE);
1308   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1309   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1310
1311   info = match_info_new (regex, string, string_len, start_position,
1312                          match_options, TRUE);
1313
1314   done = FALSE;
1315   while (!done)
1316     {
1317       done = TRUE;
1318       info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1319                                      info->string, info->string_len,
1320                                      info->pos,
1321                                      regex->match_opts | match_options,
1322                                      info->offsets, info->n_offsets,
1323                                      info->workspace, info->n_workspace);
1324       if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1325         {
1326           /* info->workspace is too small. */
1327           info->n_workspace *= 2;
1328           info->workspace = g_realloc (info->workspace,
1329                                        info->n_workspace * sizeof (gint));
1330           done = FALSE;
1331         }
1332       else if (info->matches == 0)
1333         {
1334           /* info->offsets is too small. */
1335           info->n_offsets *= 2;
1336           info->offsets = g_realloc (info->offsets,
1337                                      info->n_offsets * sizeof (gint));
1338           done = FALSE;
1339         }
1340       else if (IS_PCRE_ERROR (info->matches))
1341         {
1342           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1343                        _("Error while matching regular expression %s: %s"),
1344                        regex->pattern, match_error (info->matches));
1345         }
1346     }
1347
1348   /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1349   info->pos = -1;
1350
1351   if (match_info != NULL)
1352     *match_info = info;
1353   else
1354     g_match_info_free (info);
1355
1356   return info->matches >= 0;
1357 }
1358
1359 /**
1360  * g_regex_get_string_number:
1361  * @regex: #GRegex structure
1362  * @name: name of the subexpression
1363  *
1364  * Retrieves the number of the subexpression named @name.
1365  *
1366  * Returns: The number of the subexpression or -1 if @name does not exists
1367  *
1368  * Since: 2.14
1369  */
1370 gint
1371 g_regex_get_string_number (const GRegex *regex,
1372                            const gchar  *name)
1373 {
1374   gint num;
1375
1376   g_return_val_if_fail (regex != NULL, -1);
1377   g_return_val_if_fail (name != NULL, -1);
1378
1379   num = pcre_get_stringnumber (regex->pcre_re, name);
1380   if (num == PCRE_ERROR_NOSUBSTRING)
1381     num = -1;
1382
1383   return num;
1384 }
1385
1386 /**
1387  * g_regex_split_simple:
1388  * @pattern: the regular expression
1389  * @string: the string to scan for matches
1390  * @compile_options: compile options for the regular expression
1391  * @match_options: match options
1392  *
1393  * Breaks the string on the pattern, and returns an array of the tokens.
1394  * If the pattern contains capturing parentheses, then the text for each
1395  * of the substrings will also be returned. If the pattern does not match
1396  * anywhere in the string, then the whole string is returned as the first
1397  * token.
1398  *
1399  * This function is equivalent to g_regex_split() but it does not
1400  * require to compile the pattern with g_regex_new(), avoiding some
1401  * lines of code when you need just to do a split without extracting
1402  * substrings, capture counts, and so on.
1403  *
1404  * If this function is to be called on the same @pattern more than
1405  * once, it's more efficient to compile the pattern once with
1406  * g_regex_new() and then use g_regex_split().
1407  *
1408  * As a special case, the result of splitting the empty string "" is an
1409  * empty vector, not a vector containing a single string. The reason for
1410  * this special case is that being able to represent a empty vector is
1411  * typically more useful than consistent handling of empty elements. If
1412  * you do need to represent empty elements, you'll need to check for the
1413  * empty string before calling this function.
1414  *
1415  * A pattern that can match empty strings splits @string into separate
1416  * characters wherever it matches the empty string between characters.
1417  * For example splitting "ab c" using as a separator "\s*", you will get
1418  * "a", "b" and "c".
1419  *
1420  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1421  *
1422  * Since: 2.14
1423  **/
1424 gchar **
1425 g_regex_split_simple (const gchar        *pattern,
1426                       const gchar        *string, 
1427                       GRegexCompileFlags  compile_options,
1428                       GRegexMatchFlags    match_options)
1429 {
1430   GRegex *regex;
1431   gchar **result;
1432
1433   regex = g_regex_new (pattern, compile_options, 0, NULL);
1434   if (!regex)
1435     return NULL;
1436   result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1437   g_regex_unref (regex);
1438   return result;
1439 }
1440
1441 /**
1442  * g_regex_split:
1443  * @regex: a #GRegex structure
1444  * @string: the string to split with the pattern
1445  * @match_options: match time option flags
1446  *
1447  * Breaks the string on the pattern, and returns an array of the tokens.
1448  * If the pattern contains capturing parentheses, then the text for each
1449  * of the substrings will also be returned. If the pattern does not match
1450  * anywhere in the string, then the whole string is returned as the first
1451  * token.
1452  *
1453  * As a special case, the result of splitting the empty string "" is an
1454  * empty vector, not a vector containing a single string. The reason for
1455  * this special case is that being able to represent a empty vector is
1456  * typically more useful than consistent handling of empty elements. If
1457  * you do need to represent empty elements, you'll need to check for the
1458  * empty string before calling this function.
1459  *
1460  * A pattern that can match empty strings splits @string into separate
1461  * characters wherever it matches the empty string between characters.
1462  * For example splitting "ab c" using as a separator "\s*", you will get
1463  * "a", "b" and "c".
1464  *
1465  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1466  *
1467  * Since: 2.14
1468  **/
1469 gchar **
1470 g_regex_split (const GRegex     *regex, 
1471                const gchar      *string, 
1472                GRegexMatchFlags  match_options)
1473 {
1474   return g_regex_split_full (regex, string, -1, 0,
1475                              match_options, 0, NULL);
1476 }
1477
1478 /**
1479  * g_regex_split_full:
1480  * @regex: a #GRegex structure
1481  * @string: the string to split with the pattern
1482  * @string_len: the length of @string, or -1 if @string is nul-terminated
1483  * @start_position: starting index of the string to match
1484  * @match_options: match time option flags
1485  * @max_tokens: the maximum number of tokens to split @string into. If this
1486  *    is less than 1, the string is split completely
1487  * @error: return location for a #GError
1488  *
1489  * Breaks the string on the pattern, and returns an array of the tokens.
1490  * If the pattern contains capturing parentheses, then the text for each
1491  * of the substrings will also be returned. If the pattern does not match
1492  * anywhere in the string, then the whole string is returned as the first
1493  * token.
1494  *
1495  * As a special case, the result of splitting the empty string "" is an
1496  * empty vector, not a vector containing a single string. The reason for
1497  * this special case is that being able to represent a empty vector is
1498  * typically more useful than consistent handling of empty elements. If
1499  * you do need to represent empty elements, you'll need to check for the
1500  * empty string before calling this function.
1501  *
1502  * A pattern that can match empty strings splits @string into separate
1503  * characters wherever it matches the empty string between characters.
1504  * For example splitting "ab c" using as a separator "\s*", you will get
1505  * "a", "b" and "c".
1506  *
1507  * Setting @start_position differs from just passing over a shortened string
1508  * and  setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
1509  * with any kind of lookbehind assertion, such as "\b".
1510  *
1511  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1512  *
1513  * Since: 2.14
1514  **/
1515 gchar **
1516 g_regex_split_full (const GRegex     *regex, 
1517                     const gchar      *string, 
1518                     gssize            string_len,
1519                     gint              start_position,
1520                     GRegexMatchFlags  match_options,
1521                     gint              max_tokens,
1522                     GError          **error)
1523 {
1524   GError *tmp_error = NULL;
1525   GMatchInfo *match_info;
1526   GList *list, *last;
1527   gint i;
1528   gint token_count;
1529   gboolean match_ok;
1530   /* position of the last separator. */
1531   gint last_separator_end;
1532   /* was the last match 0 bytes long? */
1533   gboolean last_match_is_empty;
1534   /* the returned array of char **s */
1535   gchar **string_list;
1536
1537   g_return_val_if_fail (regex != NULL, NULL);
1538   g_return_val_if_fail (string != NULL, NULL);
1539   g_return_val_if_fail (start_position >= 0, NULL);
1540   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1541   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1542
1543   if (max_tokens <= 0)
1544     max_tokens = G_MAXINT;
1545
1546   if (string_len < 0)
1547     string_len = strlen (string);
1548
1549   /* zero-length string */
1550   if (string_len - start_position == 0)
1551     return g_new0 (gchar *, 1);
1552
1553   if (max_tokens == 1)
1554     {
1555       string_list = g_new0 (gchar *, 2);
1556       string_list[0] = g_strndup (&string[start_position],
1557                                   string_len - start_position);
1558       return string_list;
1559     }
1560
1561   list = NULL;
1562   token_count = 0;
1563   last_separator_end = start_position;
1564   last_match_is_empty = FALSE;
1565
1566   match_ok = g_regex_match_full (regex, string, string_len, start_position,
1567                                  match_options, &match_info, &tmp_error);
1568   while (tmp_error == NULL)
1569     {
1570       if (match_ok)
1571         {
1572           last_match_is_empty =
1573                     (match_info->offsets[0] == match_info->offsets[1]);
1574
1575           /* we need to skip empty separators at the same position of the end
1576            * of another separator. e.g. the string is "a b" and the separator
1577            * is " *", so from 1 to 2 we have a match and at position 2 we have
1578            * an empty match. */
1579           if (last_separator_end != match_info->offsets[1])
1580             {
1581               gchar *token;
1582               gint match_count;
1583
1584               token = g_strndup (string + last_separator_end,
1585                                  match_info->offsets[0] - last_separator_end);
1586               list = g_list_prepend (list, token);
1587               token_count++;
1588
1589               /* if there were substrings, these need to be added to
1590                * the list. */
1591               match_count = g_match_info_get_match_count (match_info);
1592               if (match_count > 1)
1593                 {
1594                   for (i = 1; i < match_count; i++)
1595                     list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1596                 }
1597             }
1598         }
1599       else
1600         {
1601           /* if there was no match, copy to end of string. */
1602           if (!last_match_is_empty)
1603             {
1604               gchar *token = g_strndup (string + last_separator_end,
1605                                         match_info->string_len - last_separator_end);
1606               list = g_list_prepend (list, token);
1607             }
1608           /* no more tokens, end the loop. */
1609           break;
1610         }
1611
1612       /* -1 to leave room for the last part. */
1613       if (token_count >= max_tokens - 1)
1614         {
1615           /* we have reached the maximum number of tokens, so we copy
1616            * the remaining part of the string. */
1617           if (last_match_is_empty)
1618             {
1619               /* the last match was empty, so we have moved one char
1620                * after the real position to avoid empty matches at the
1621                * same position. */
1622               match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1623             }
1624           /* the if is needed in the case we have terminated the available
1625            * tokens, but we are at the end of the string, so there are no
1626            * characters left to copy. */
1627           if (string_len > match_info->pos)
1628             {
1629               gchar *token = g_strndup (string + match_info->pos,
1630                                         string_len - match_info->pos);
1631               list = g_list_prepend (list, token);
1632             }
1633           /* end the loop. */
1634           break;
1635         }
1636
1637       last_separator_end = match_info->pos;
1638       if (last_match_is_empty)
1639         /* if the last match was empty, g_match_info_next() has moved
1640          * forward to avoid infinite loops, but we still need to copy that
1641          * character. */
1642         last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1643
1644       match_ok = g_match_info_next (match_info, &tmp_error);
1645     }
1646   g_match_info_free (match_info);
1647   if (tmp_error != NULL)
1648     {
1649       g_propagate_error (error, tmp_error);
1650       g_list_foreach (list, (GFunc)g_free, NULL);
1651       g_list_free (list);
1652       match_info->pos = -1;
1653       return NULL;
1654     }
1655
1656   string_list = g_new (gchar *, g_list_length (list) + 1);
1657   i = 0;
1658   for (last = g_list_last (list); last; last = g_list_previous (last))
1659     string_list[i++] = last->data;
1660   string_list[i] = 0;
1661   g_list_free (list);
1662
1663   return string_list;
1664 }
1665
1666 enum
1667 {
1668   REPL_TYPE_STRING,
1669   REPL_TYPE_CHARACTER,
1670   REPL_TYPE_SYMBOLIC_REFERENCE,
1671   REPL_TYPE_NUMERIC_REFERENCE,
1672   REPL_TYPE_CHANGE_CASE
1673 }; 
1674
1675 typedef enum
1676 {
1677   CHANGE_CASE_NONE         = 1 << 0,
1678   CHANGE_CASE_UPPER        = 1 << 1,
1679   CHANGE_CASE_LOWER        = 1 << 2,
1680   CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1681   CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1682   CHANGE_CASE_SINGLE_MASK  = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1683   CHANGE_CASE_LOWER_MASK   = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1684   CHANGE_CASE_UPPER_MASK   = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1685 } ChangeCase;
1686
1687 struct _InterpolationData
1688 {
1689   gchar     *text;   
1690   gint       type;   
1691   gint       num;
1692   gchar      c;
1693   ChangeCase change_case;
1694 };
1695
1696 static void
1697 free_interpolation_data (InterpolationData *data)
1698 {
1699   g_free (data->text);
1700   g_free (data);
1701 }
1702
1703 static const gchar *
1704 expand_escape (const gchar        *replacement,
1705                const gchar        *p, 
1706                InterpolationData  *data,
1707                GError            **error)
1708 {
1709   const gchar *q, *r;
1710   gint x, d, h, i;
1711   const gchar *error_detail;
1712   gint base = 0;
1713   GError *tmp_error = NULL;
1714
1715   p++;
1716   switch (*p)
1717     {
1718     case 't':
1719       p++;
1720       data->c = '\t';
1721       data->type = REPL_TYPE_CHARACTER;
1722       break;
1723     case 'n':
1724       p++;
1725       data->c = '\n';
1726       data->type = REPL_TYPE_CHARACTER;
1727       break;
1728     case 'v':
1729       p++;
1730       data->c = '\v';
1731       data->type = REPL_TYPE_CHARACTER;
1732       break;
1733     case 'r':
1734       p++;
1735       data->c = '\r';
1736       data->type = REPL_TYPE_CHARACTER;
1737       break;
1738     case 'f':
1739       p++;
1740       data->c = '\f';
1741       data->type = REPL_TYPE_CHARACTER;
1742       break;
1743     case 'a':
1744       p++;
1745       data->c = '\a';
1746       data->type = REPL_TYPE_CHARACTER;
1747       break;
1748     case 'b':
1749       p++;
1750       data->c = '\b';
1751       data->type = REPL_TYPE_CHARACTER;
1752       break;
1753     case '\\':
1754       p++;
1755       data->c = '\\';
1756       data->type = REPL_TYPE_CHARACTER;
1757       break;
1758     case 'x':
1759       p++;
1760       x = 0;
1761       if (*p == '{')
1762         {
1763           p++;
1764           do 
1765             {
1766               h = g_ascii_xdigit_value (*p);
1767               if (h < 0)
1768                 {
1769                   error_detail = _("hexadecimal digit or '}' expected");
1770                   goto error;
1771                 }
1772               x = x * 16 + h;
1773               p++;
1774             }
1775           while (*p != '}');
1776           p++;
1777         }
1778       else
1779         {
1780           for (i = 0; i < 2; i++)
1781             {
1782               h = g_ascii_xdigit_value (*p);
1783               if (h < 0)
1784                 {
1785                   error_detail = _("hexadecimal digit expected");
1786                   goto error;
1787                 }
1788               x = x * 16 + h;
1789               p++;
1790             }
1791         }
1792       data->type = REPL_TYPE_STRING;
1793       data->text = g_new0 (gchar, 8);
1794       g_unichar_to_utf8 (x, data->text);
1795       break;
1796     case 'l':
1797       p++;
1798       data->type = REPL_TYPE_CHANGE_CASE;
1799       data->change_case = CHANGE_CASE_LOWER_SINGLE;
1800       break;
1801     case 'u':
1802       p++;
1803       data->type = REPL_TYPE_CHANGE_CASE;
1804       data->change_case = CHANGE_CASE_UPPER_SINGLE;
1805       break;
1806     case 'L':
1807       p++;
1808       data->type = REPL_TYPE_CHANGE_CASE;
1809       data->change_case = CHANGE_CASE_LOWER;
1810       break;
1811     case 'U':
1812       p++;
1813       data->type = REPL_TYPE_CHANGE_CASE;
1814       data->change_case = CHANGE_CASE_UPPER;
1815       break;
1816     case 'E':
1817       p++;
1818       data->type = REPL_TYPE_CHANGE_CASE;
1819       data->change_case = CHANGE_CASE_NONE;
1820       break;
1821     case 'g':
1822       p++;
1823       if (*p != '<')
1824         {
1825           error_detail = _("missing '<' in symbolic reference");
1826           goto error;
1827         }
1828       q = p + 1;
1829       do 
1830         {
1831           p++;
1832           if (!*p)
1833             {
1834               error_detail = _("unfinished symbolic reference");
1835               goto error;
1836             }
1837         }
1838       while (*p != '>');
1839       if (p - q == 0)
1840         {
1841           error_detail = _("zero-length symbolic reference");
1842           goto error;
1843         }
1844       if (g_ascii_isdigit (*q))
1845         {
1846           x = 0;
1847           do 
1848             {
1849               h = g_ascii_digit_value (*q);
1850               if (h < 0)
1851                 {
1852                   error_detail = _("digit expected");
1853                   p = q;
1854                   goto error;
1855                 }
1856               x = x * 10 + h;
1857               q++;
1858             }
1859           while (q != p);
1860           data->num = x;
1861           data->type = REPL_TYPE_NUMERIC_REFERENCE;
1862         }
1863       else
1864         {
1865           r = q;
1866           do 
1867             {
1868               if (!g_ascii_isalnum (*r))
1869                 {
1870                   error_detail = _("illegal symbolic reference");
1871                   p = r;
1872                   goto error;
1873                 }
1874               r++;
1875             }
1876           while (r != p);
1877           data->text = g_strndup (q, p - q);
1878           data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
1879         }
1880       p++;
1881       break;
1882     case '0':
1883       /* if \0 is followed by a number is an octal number representing a
1884        * character, else it is a numeric reference. */
1885       if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
1886         {
1887           base = 8;
1888           p = g_utf8_next_char (p);
1889         }
1890     case '1':
1891     case '2':
1892     case '3':
1893     case '4':
1894     case '5':
1895     case '6':
1896     case '7':
1897     case '8':
1898     case '9':
1899       x = 0;
1900       d = 0;
1901       for (i = 0; i < 3; i++)
1902         {
1903           h = g_ascii_digit_value (*p);
1904           if (h < 0) 
1905             break;
1906           if (h > 7)
1907             {
1908               if (base == 8)
1909                 break;
1910               else 
1911                 base = 10;
1912             }
1913           if (i == 2 && base == 10)
1914             break;
1915           x = x * 8 + h;
1916           d = d * 10 + h;
1917           p++;
1918         }
1919       if (base == 8 || i == 3)
1920         {
1921           data->type = REPL_TYPE_STRING;
1922           data->text = g_new0 (gchar, 8);
1923           g_unichar_to_utf8 (x, data->text);
1924         }
1925       else
1926         {
1927           data->type = REPL_TYPE_NUMERIC_REFERENCE;
1928           data->num = d;
1929         }
1930       break;
1931     case 0:
1932       error_detail = _("stray final '\\'");
1933       goto error;
1934       break;
1935     default:
1936       error_detail = _("unknown escape sequence");
1937       goto error;
1938     }
1939
1940   return p;
1941
1942  error:
1943   /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
1944   tmp_error = g_error_new (G_REGEX_ERROR, 
1945                            G_REGEX_ERROR_REPLACE,
1946                            _("Error while parsing replacement "
1947                              "text \"%s\" at char %lu: %s"),
1948                            replacement, 
1949                            (gulong)(p - replacement),
1950                            error_detail);
1951   g_propagate_error (error, tmp_error);
1952
1953   return NULL;
1954 }
1955
1956 static GList *
1957 split_replacement (const gchar  *replacement,
1958                    GError      **error)
1959 {
1960   GList *list = NULL;
1961   InterpolationData *data;
1962   const gchar *p, *start;
1963   
1964   start = p = replacement; 
1965   while (*p)
1966     {
1967       if (*p == '\\')
1968         {
1969           data = g_new0 (InterpolationData, 1);
1970           start = p = expand_escape (replacement, p, data, error);
1971           if (p == NULL)
1972             {
1973               g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
1974               g_list_free (list);
1975               free_interpolation_data (data);
1976
1977               return NULL;
1978             }
1979           list = g_list_prepend (list, data);
1980         }
1981       else
1982         {
1983           p++;
1984           if (*p == '\\' || *p == '\0')
1985             {
1986               if (p - start > 0)
1987                 {
1988                   data = g_new0 (InterpolationData, 1);
1989                   data->text = g_strndup (start, p - start);
1990                   data->type = REPL_TYPE_STRING;
1991                   list = g_list_prepend (list, data);
1992                 }
1993             }
1994         }
1995     }
1996
1997   return g_list_reverse (list);
1998 }
1999
2000 /* Change the case of c based on change_case. */
2001 #define CHANGE_CASE(c, change_case) \
2002         (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2003                 g_unichar_tolower (c) : \
2004                 g_unichar_toupper (c))
2005
2006 static void
2007 string_append (GString     *string,
2008                const gchar *text,
2009                ChangeCase  *change_case)
2010 {
2011   gunichar c;
2012
2013   if (text[0] == '\0')
2014     return;
2015
2016   if (*change_case == CHANGE_CASE_NONE)
2017     {
2018       g_string_append (string, text);
2019     }
2020   else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2021     {
2022       c = g_utf8_get_char (text);
2023       g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2024       g_string_append (string, g_utf8_next_char (text));
2025       *change_case = CHANGE_CASE_NONE;
2026     }
2027   else
2028     {
2029       while (*text != '\0')
2030         {
2031           c = g_utf8_get_char (text);
2032           g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2033           text = g_utf8_next_char (text);
2034         }
2035     }
2036 }
2037
2038 static gboolean
2039 interpolate_replacement (const GMatchInfo *match_info,
2040                          GString          *result,
2041                          gpointer          data)
2042 {
2043   GList *list;
2044   InterpolationData *idata;
2045   gchar *match;
2046   ChangeCase change_case = CHANGE_CASE_NONE;
2047
2048   for (list = data; list; list = list->next)
2049     {
2050       idata = list->data;
2051       switch (idata->type)
2052         {
2053         case REPL_TYPE_STRING:
2054           string_append (result, idata->text, &change_case);
2055           break;
2056         case REPL_TYPE_CHARACTER:
2057           g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2058           if (change_case & CHANGE_CASE_SINGLE_MASK)
2059             change_case = CHANGE_CASE_NONE;
2060           break;
2061         case REPL_TYPE_NUMERIC_REFERENCE:
2062           match = g_match_info_fetch (match_info, idata->num);
2063           if (match)
2064             {
2065               string_append (result, match, &change_case);
2066               g_free (match);
2067             }
2068           break;
2069         case REPL_TYPE_SYMBOLIC_REFERENCE:
2070           match = g_match_info_fetch_named (match_info, idata->text);
2071           if (match)
2072             {
2073               string_append (result, match, &change_case);
2074               g_free (match);
2075             }
2076           break;
2077         case REPL_TYPE_CHANGE_CASE:
2078           change_case = idata->change_case;
2079           break;
2080         }
2081     }
2082
2083   return FALSE; 
2084 }
2085
2086 /* whether actual match_info is needed for replacement, i.e.
2087  * whether there are references
2088  */
2089 static gboolean
2090 interpolation_list_needs_match (GList *list)
2091 {
2092   while (list != NULL)
2093     {
2094       InterpolationData *data = list->data;
2095
2096       if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2097           data->type == REPL_TYPE_NUMERIC_REFERENCE)
2098         {
2099           return TRUE;
2100         }
2101
2102       list = list->next;
2103     }
2104
2105   return FALSE;
2106 }
2107
2108 /**
2109  * g_regex_replace:
2110  * @regex: a #GRegex structure
2111  * @string: the string to perform matches against
2112  * @string_len: the length of @string, or -1 if @string is nul-terminated
2113  * @start_position: starting index of the string to match
2114  * @replacement: text to replace each match with
2115  * @match_options: options for the match
2116  * @error: location to store the error occuring, or %NULL to ignore errors
2117  *
2118  * Replaces all occurances of the pattern in @regex with the
2119  * replacement text. Backreferences of the form '\number' or '\g&lt;number&gt;'
2120  * in the replacement text are interpolated by the number-th captured
2121  * subexpression of the match, '\g&lt;name&gt;' refers to the captured subexpression
2122  * with the given name. '\0' refers to the complete match, but '\0' followed
2123  * by a number is the octal representation of a character. To include a
2124  * literal '\' in the replacement, write '\\'.
2125  * There are also escapes that changes the case of the following text:
2126  *
2127  * <variablelist>
2128  * <varlistentry><term>\l</term>
2129  * <listitem>
2130  * <para>Convert to lower case the next character</para>
2131  * </listitem>
2132  * </varlistentry>
2133  * <varlistentry><term>\u</term>
2134  * <listitem>
2135  * <para>Convert to upper case the next character</para>
2136  * </listitem>
2137  * </varlistentry>
2138  * <varlistentry><term>\L</term>
2139  * <listitem>
2140  * <para>Convert to lower case till \E</para>
2141  * </listitem>
2142  * </varlistentry>
2143  * <varlistentry><term>\U</term>
2144  * <listitem>
2145  * <para>Convert to upper case till \E</para>
2146  * </listitem>
2147  * </varlistentry>
2148  * <varlistentry><term>\E</term>
2149  * <listitem>
2150  * <para>End case modification</para>
2151  * </listitem>
2152  * </varlistentry>
2153  * </variablelist>
2154  *
2155  * If you do not need to use backreferences use g_regex_replace_literal().
2156  *
2157  * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2158  * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2159  * you can use g_regex_replace_literal().
2160  *
2161  * Setting @start_position differs from just passing over a shortened string
2162  * and  setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2163  * with any kind of lookbehind assertion, such as "\b".
2164  *
2165  * Returns: a newly allocated string containing the replacements
2166  *
2167  * Since: 2.14
2168  */
2169 gchar *
2170 g_regex_replace (const GRegex      *regex, 
2171                  const gchar       *string, 
2172                  gssize             string_len,
2173                  gint               start_position,
2174                  const gchar       *replacement,
2175                  GRegexMatchFlags   match_options,
2176                  GError           **error)
2177 {
2178   gchar *result;
2179   GList *list;
2180   GError *tmp_error = NULL;
2181
2182   g_return_val_if_fail (regex != NULL, NULL);
2183   g_return_val_if_fail (string != NULL, NULL);
2184   g_return_val_if_fail (start_position >= 0, NULL);
2185   g_return_val_if_fail (replacement != NULL, NULL);
2186   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2187   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2188
2189   list = split_replacement (replacement, &tmp_error);
2190   if (tmp_error != NULL)
2191     {
2192       g_propagate_error (error, tmp_error);
2193       return NULL;
2194     }
2195
2196   result = g_regex_replace_eval (regex, 
2197                                  string, string_len, start_position,
2198                                  match_options,
2199                                  interpolate_replacement,
2200                                  (gpointer)list,
2201                                  &tmp_error);
2202   if (tmp_error != NULL)
2203     g_propagate_error (error, tmp_error);
2204
2205   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2206   g_list_free (list);
2207
2208   return result;
2209 }
2210
2211 static gboolean
2212 literal_replacement (const GMatchInfo *match_info,
2213                      GString          *result,
2214                      gpointer          data)
2215 {
2216   g_string_append (result, data);
2217   return FALSE;
2218 }
2219
2220 /**
2221  * g_regex_replace_literal:
2222  * @regex: a #GRegex structure
2223  * @string: the string to perform matches against
2224  * @string_len: the length of @string, or -1 if @string is nul-terminated
2225  * @start_position: starting index of the string to match
2226  * @replacement: text to replace each match with
2227  * @match_options: options for the match
2228  * @error: location to store the error occuring, or %NULL to ignore errors
2229  *
2230  * Replaces all occurances of the pattern in @regex with the
2231  * replacement text. @replacement is replaced literally, to
2232  * include backreferences use g_regex_replace().
2233  *
2234  * Setting @start_position differs from just passing over a shortened string
2235  * and  setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2236  * with any kind of lookbehind assertion, such as "\b".
2237  *
2238  * Returns: a newly allocated string containing the replacements
2239  *
2240  * Since: 2.14
2241  */
2242 gchar *
2243 g_regex_replace_literal (const GRegex    *regex,
2244                          const gchar     *string,
2245                          gssize           string_len,
2246                          gint             start_position,
2247                          const gchar     *replacement,
2248                          GRegexMatchFlags match_options,
2249                          GError         **error)
2250 {
2251   g_return_val_if_fail (replacement != NULL, NULL);
2252   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2253
2254   return g_regex_replace_eval (regex,
2255                                string, string_len, start_position,
2256                                match_options,
2257                                literal_replacement,
2258                                (gpointer)replacement,
2259                                error);
2260 }
2261
2262 /**
2263  * g_regex_replace_eval:
2264  * @regex: a #GRegex structure from g_regex_new()
2265  * @string: string to perform matches against
2266  * @string_len: the length of @string, or -1 if @string is nul-terminated
2267  * @start_position: starting index of the string to match
2268  * @match_options: options for the match
2269  * @eval: a function to call for each match
2270  * @user_data: user data to pass to the function
2271  * @error: location to store the error occuring, or %NULL to ignore errors
2272  *
2273  * Replaces occurances of the pattern in regex with the output of @eval
2274  * for that occurance.
2275  *
2276  * Setting @start_position differs from just passing over a shortened string
2277  * and  setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that begins
2278  * with any kind of lookbehind assertion, such as "\b".
2279  *
2280  * Returns: a newly allocated string containing the replacements
2281  *
2282  * Since: 2.14
2283  */
2284 gchar *
2285 g_regex_replace_eval (const GRegex      *regex,
2286                       const gchar       *string,
2287                       gssize             string_len,
2288                       gint               start_position,
2289                       GRegexMatchFlags   match_options,
2290                       GRegexEvalCallback eval,
2291                       gpointer           user_data,
2292                       GError           **error)
2293 {
2294   GMatchInfo *match_info;
2295   GString *result;
2296   gint str_pos = 0;
2297   gboolean done = FALSE;
2298   GError *tmp_error = NULL;
2299
2300   g_return_val_if_fail (regex != NULL, NULL);
2301   g_return_val_if_fail (string != NULL, NULL);
2302   g_return_val_if_fail (start_position >= 0, NULL);
2303   g_return_val_if_fail (eval != NULL, NULL);
2304   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2305
2306   if (string_len < 0)
2307     string_len = strlen (string);
2308
2309   result = g_string_sized_new (string_len);
2310
2311   /* run down the string making matches. */
2312   g_regex_match_full (regex, string, string_len, start_position,
2313                       match_options, &match_info, &tmp_error);
2314   while (!done && g_match_info_matches (match_info))
2315     {
2316       g_string_append_len (result,
2317                            string + str_pos,
2318                            match_info->offsets[0] - str_pos);
2319       done = (*eval) (match_info, result, user_data);
2320       str_pos = match_info->offsets[1];
2321       g_match_info_next (match_info, &tmp_error);
2322     }
2323   g_match_info_free (match_info);
2324   if (tmp_error != NULL)
2325     {
2326       g_propagate_error (error, tmp_error);
2327       g_string_free (result, TRUE);
2328       return NULL;
2329     }
2330
2331   g_string_append_len (result, string + str_pos, string_len - str_pos);
2332   return g_string_free (result, FALSE);
2333 }
2334
2335 /**
2336  * g_regex_check_replacement:
2337  * @replacement: the replacement string
2338  * @has_references: location to store information about
2339  * references in @replacement or %NULL
2340  * @error: location to store error
2341  *
2342  * Checks whether @replacement is a valid replacement string (see g_regex_replace()),
2343  * i.e. that all escape sequences in it are valid.
2344  *
2345  * If @has_references is not %NULL then @replacement is checked for
2346  * pattern references. For instance, replacement text 'foo\n'
2347  * does not contain references and may be evaluated without information
2348  * about actual match, but '\0\1' (whole match followed by first subpattern)
2349  * requires valid #GMatchInfo object.
2350  *
2351  * Returns: whether @replacement is a valid replacement string
2352  *
2353  * Since: 2.14
2354  */
2355 gboolean
2356 g_regex_check_replacement (const gchar  *replacement,
2357                            gboolean     *has_references,
2358                            GError      **error)
2359 {
2360   GList *list;
2361   GError *tmp = NULL;
2362
2363   list = split_replacement (replacement, &tmp);
2364
2365   if (tmp)
2366   {
2367     g_propagate_error (error, tmp);
2368     return FALSE;
2369   }
2370
2371   if (has_references)
2372     *has_references = interpolation_list_needs_match (list);
2373
2374   g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2375   g_list_free (list);
2376
2377   return TRUE;
2378 }
2379
2380 /**
2381  * g_regex_escape_string:
2382  * @string: the string to escape
2383  * @length: the length of @string, or -1 if @string is nul-terminated
2384  *
2385  * Escapes the special characters used for regular expressions in @string,
2386  * for instance "a.b*c" becomes "a\.b\*c". This function is useful to
2387  * dynamically generate regular expressions.
2388  *
2389  * @string can contain nul characters that are replaced with "\0", in this
2390  * case remember to specify the correct length of @string in @length.
2391  *
2392  * Returns: a newly-allocated escaped string
2393  *
2394  * Since: 2.14
2395  */
2396 gchar *
2397 g_regex_escape_string (const gchar *string,
2398                        gint         length)
2399 {
2400   GString *escaped;
2401   const char *p, *piece_start, *end;
2402
2403   g_return_val_if_fail (string != NULL, NULL);
2404
2405   if (length < 0)
2406     length = strlen (string);
2407
2408   end = string + length;
2409   p = piece_start = string;
2410   escaped = g_string_sized_new (length + 1);
2411
2412   while (p < end)
2413     {
2414       switch (*p)
2415         {
2416         case '\0':
2417         case '\\':
2418         case '|':
2419         case '(':
2420         case ')':
2421         case '[':
2422         case ']':
2423         case '{':
2424         case '}':
2425         case '^':
2426         case '$':
2427         case '*':
2428         case '+':
2429         case '?':
2430         case '.':
2431           if (p != piece_start)
2432             /* copy the previous piece. */
2433             g_string_append_len (escaped, piece_start, p - piece_start);
2434           g_string_append_c (escaped, '\\');
2435           if (*p == '\0')
2436             g_string_append_c (escaped, '0');
2437           else
2438             g_string_append_c (escaped, *p);
2439           piece_start = ++p;
2440           break;
2441         default:
2442           p = g_utf8_next_char (p);
2443           break;
2444         } 
2445   }
2446
2447   if (piece_start < end)
2448     g_string_append_len (escaped, piece_start, end - piece_start);
2449
2450   return g_string_free (escaped, FALSE);
2451 }
2452
2453 #define __G_REGEX_C__
2454 #include "galiasdef.c"