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