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