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