Add introspection annotations in gregex.c
[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 <string.h>
25
26 #include "glib.h"
27 #include "glibintl.h"
28 #include "gregex.h"
29
30 #ifdef USE_SYSTEM_PCRE
31 #include <pcre.h>
32 #else
33 #include "pcre/pcre.h"
34 #endif
35
36 /* PCRE 7.3 does not contain the definition of PCRE_ERROR_NULLWSLIMIT */
37 #ifndef PCRE_ERROR_NULLWSLIMIT
38 #define PCRE_ERROR_NULLWSLIMIT (-22)
39 #endif
40
41
42 /* Mask of all the possible values for GRegexCompileFlags. */
43 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS          | \
44                               G_REGEX_MULTILINE         | \
45                               G_REGEX_DOTALL            | \
46                               G_REGEX_EXTENDED          | \
47                               G_REGEX_ANCHORED          | \
48                               G_REGEX_DOLLAR_ENDONLY    | \
49                               G_REGEX_UNGREEDY          | \
50                               G_REGEX_RAW               | \
51                               G_REGEX_NO_AUTO_CAPTURE   | \
52                               G_REGEX_OPTIMIZE          | \
53                               G_REGEX_DUPNAMES          | \
54                               G_REGEX_NEWLINE_CR        | \
55                               G_REGEX_NEWLINE_LF        | \
56                               G_REGEX_NEWLINE_CRLF)
57
58 /* Mask of all the possible values for GRegexMatchFlags. */
59 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED      | \
60                             G_REGEX_MATCH_NOTBOL        | \
61                             G_REGEX_MATCH_NOTEOL        | \
62                             G_REGEX_MATCH_NOTEMPTY      | \
63                             G_REGEX_MATCH_PARTIAL       | \
64                             G_REGEX_MATCH_NEWLINE_CR    | \
65                             G_REGEX_MATCH_NEWLINE_LF    | \
66                             G_REGEX_MATCH_NEWLINE_CRLF  | \
67                             G_REGEX_MATCH_NEWLINE_ANY)
68
69 /* if the string is in UTF-8 use g_utf8_ functions, else use
70  * use just +/- 1. */
71 #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
72                                 g_utf8_next_char (s) : \
73                                 ((s) + 1))
74 #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
75                                 g_utf8_prev_char (s) : \
76                                 ((s) - 1))
77
78 struct _GMatchInfo
79 {
80   GRegex *regex;                /* the regex */
81   GRegexMatchFlags match_opts;  /* options used at match time on the regex */
82   gint matches;                 /* number of matching sub patterns */
83   gint pos;                     /* position in the string where last match left off */
84   gint *offsets;                /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
85   gint n_offsets;               /* number of offsets */
86   gint *workspace;              /* workspace for pcre_dfa_exec() */
87   gint n_workspace;             /* number of workspace elements */
88   const gchar *string;          /* string passed to the match function */
89   gssize string_len;            /* length of string */
90 };
91
92 struct _GRegex
93 {
94   volatile gint ref_count;      /* the ref count for the immutable part */
95   gchar *pattern;               /* the pattern */
96   pcre *pcre_re;                /* compiled form of the pattern */
97   GRegexCompileFlags compile_opts;      /* options used at compile time on the pattern */
98   GRegexMatchFlags match_opts;  /* options used at match time on the regex */
99   pcre_extra *extra;            /* data stored when G_REGEX_OPTIMIZE is used */
100 };
101
102 /* TRUE if ret is an error code, FALSE otherwise. */
103 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
104
105 typedef struct _InterpolationData InterpolationData;
106 static gboolean  interpolation_list_needs_match (GList *list);
107 static gboolean  interpolate_replacement        (const GMatchInfo *match_info,
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 static void
182 translate_compile_error (gint *errcode, const gchar **errmsg)
183 {
184   /* Compile errors are created adding 100 to the error code returned
185    * by PCRE.
186    * If errcode is known we put the translatable error message in
187    * erromsg. If errcode is unknown we put the generic
188    * G_REGEX_ERROR_COMPILE error code in errcode and keep the
189    * untranslated error message returned by PCRE.
190    * Note that there can be more PCRE errors with the same GRegexError
191    * and that some PCRE errors are useless for us.
192    */
193   *errcode += 100;
194
195   switch (*errcode)
196     {
197     case G_REGEX_ERROR_STRAY_BACKSLASH:
198       *errmsg = _("\\ at end of pattern");
199       break;
200     case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
201       *errmsg = _("\\c at end of pattern");
202       break;
203     case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
204       *errmsg = _("unrecognized character follows \\");
205       break;
206     case 137:
207       /* A number of Perl escapes are not handled by PCRE.
208        * Therefore it explicitly raises ERR37.
209        */
210       *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
211       *errmsg = _("case-changing escapes (\\l, \\L, \\u, \\U) are not allowed here");
212       break;
213     case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
214       *errmsg = _("numbers out of order in {} quantifier");
215       break;
216     case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
217       *errmsg = _("number too big in {} quantifier");
218       break;
219     case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
220       *errmsg = _("missing terminating ] for character class");
221       break;
222     case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
223       *errmsg = _("invalid escape sequence in character class");
224       break;
225     case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
226       *errmsg = _("range out of order in character class");
227       break;
228     case G_REGEX_ERROR_NOTHING_TO_REPEAT:
229       *errmsg = _("nothing to repeat");
230       break;
231     case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
232       *errmsg = _("unrecognized character after (?");
233       break;
234     case 124:
235       *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
236       *errmsg = _("unrecognized character after (?<");
237       break;
238     case 141:
239       *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
240       *errmsg = _("unrecognized character after (?P");
241       break;
242     case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
243       *errmsg = _("POSIX named classes are supported only within a class");
244       break;
245     case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
246       *errmsg = _("missing terminating )");
247       break;
248     case 122:
249       *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
250       *errmsg = _(") without opening (");
251       break;
252     case 129:
253       *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
254       /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of) 
255        * sequences here, '(?-54' would be an example for the second group.
256        */
257       *errmsg = _("(?R or (?[+-]digits must be followed by )");
258       break;
259     case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
260       *errmsg = _("reference to non-existent subpattern");
261       break;
262     case G_REGEX_ERROR_UNTERMINATED_COMMENT:
263       *errmsg = _("missing ) after comment");
264       break;
265     case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
266       *errmsg = _("regular expression too large");
267       break;
268     case G_REGEX_ERROR_MEMORY_ERROR:
269       *errmsg = _("failed to get memory");
270       break;
271     case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
272       *errmsg = _("lookbehind assertion is not fixed length");
273       break;
274     case G_REGEX_ERROR_MALFORMED_CONDITION:
275       *errmsg = _("malformed number or name after (?(");
276       break;
277     case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
278       *errmsg = _("conditional group contains more than two branches");
279       break;
280     case G_REGEX_ERROR_ASSERTION_EXPECTED:
281       *errmsg = _("assertion expected after (?(");
282       break;
283     case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
284       *errmsg = _("unknown POSIX class name");
285       break;
286     case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
287       *errmsg = _("POSIX collating elements are not supported");
288       break;
289     case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
290       *errmsg = _("character value in \\x{...} sequence is too large");
291       break;
292     case G_REGEX_ERROR_INVALID_CONDITION:
293       *errmsg = _("invalid condition (?(0)");
294       break;
295     case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
296       *errmsg = _("\\C not allowed in lookbehind assertion");
297       break;
298     case G_REGEX_ERROR_INFINITE_LOOP:
299       *errmsg = _("recursive call could loop indefinitely");
300       break;
301     case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
302       *errmsg = _("missing terminator in subpattern name");
303       break;
304     case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
305       *errmsg = _("two named subpatterns have the same name");
306       break;
307     case G_REGEX_ERROR_MALFORMED_PROPERTY:
308       *errmsg = _("malformed \\P or \\p sequence");
309       break;
310     case G_REGEX_ERROR_UNKNOWN_PROPERTY:
311       *errmsg = _("unknown property name after \\P or \\p");
312       break;
313     case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
314       *errmsg = _("subpattern name is too long (maximum 32 characters)");
315       break;
316     case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
317       *errmsg = _("too many named subpatterns (maximum 10,000)");
318       break;
319     case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
320       *errmsg = _("octal value is greater than \\377");
321       break;
322     case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
323       *errmsg = _("DEFINE group contains more than one branch");
324       break;
325     case G_REGEX_ERROR_DEFINE_REPETION:
326       *errmsg = _("repeating a DEFINE group is not allowed");
327       break;
328     case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
329       *errmsg = _("inconsistent NEWLINE options");
330       break;
331     case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
332       *errmsg = _("\\g is not followed by a braced name or an optionally "
333                  "braced non-zero number");
334       break;
335     case 11:
336       *errcode = G_REGEX_ERROR_INTERNAL;
337       *errmsg = _("unexpected repeat");
338       break;
339     case 23:
340       *errcode = G_REGEX_ERROR_INTERNAL;
341       *errmsg = _("code overflow");
342       break;
343     case 52:
344       *errcode = G_REGEX_ERROR_INTERNAL;
345       *errmsg = _("overran compiling workspace");
346       break;
347     case 53:
348       *errcode = G_REGEX_ERROR_INTERNAL;
349       *errmsg = _("previously-checked referenced subpattern not found");
350       break;
351     case 16:
352       /* This should not happen as we never pass a NULL erroffset */
353       g_warning ("erroffset passed as NULL");
354       *errcode = G_REGEX_ERROR_COMPILE;
355       break;
356     case 17:
357       /* This should not happen as we check options before passing them
358        * to pcre_compile2() */
359       g_warning ("unknown option bit(s) set");
360       *errcode = G_REGEX_ERROR_COMPILE;
361       break;
362     case 32:
363     case 44:
364     case 45:
365       /* These errors should not happen as we are using an UTF8-enabled PCRE
366        * and we do not check if strings are valid */
367       g_warning ("%s", *errmsg);
368       *errcode = G_REGEX_ERROR_COMPILE;
369       break;
370     default:
371       *errcode = G_REGEX_ERROR_COMPILE;
372     }
373 }
374
375 /* GMatchInfo */
376
377 static GMatchInfo *
378 match_info_new (const GRegex *regex,
379                 const gchar  *string,
380                 gint          string_len,
381                 gint          start_position,
382                 gint          match_options,
383                 gboolean      is_dfa)
384 {
385   GMatchInfo *match_info;
386
387   if (string_len < 0)
388     string_len = strlen (string);
389
390   match_info = g_new0 (GMatchInfo, 1);
391   match_info->regex = g_regex_ref ((GRegex *)regex);
392   match_info->string = string;
393   match_info->string_len = string_len;
394   match_info->matches = PCRE_ERROR_NOMATCH;
395   match_info->pos = start_position;
396   match_info->match_opts = match_options;
397
398   if (is_dfa)
399     {
400       /* These values should be enough for most cases, if they are not
401        * enough g_regex_match_all_full() will expand them. */
402       match_info->n_offsets = 24;
403       match_info->n_workspace = 100;
404       match_info->workspace = g_new (gint, match_info->n_workspace);
405     }
406   else
407     {
408       gint capture_count;
409       pcre_fullinfo (regex->pcre_re, regex->extra,
410                      PCRE_INFO_CAPTURECOUNT, &capture_count);
411       match_info->n_offsets = (capture_count + 1) * 3;
412     }
413
414   match_info->offsets = g_new0 (gint, match_info->n_offsets);
415   /* Set an invalid position for the previous match. */
416   match_info->offsets[0] = -1;
417   match_info->offsets[1] = -1;
418
419   return match_info;
420 }
421
422 /**
423  * g_match_info_get_regex:
424  * @match_info: a #GMatchInfo
425  *
426  * Returns #GRegex object used in @match_info. It belongs to Glib
427  * and must not be freed. Use g_regex_ref() if you need to keep it
428  * after you free @match_info object.
429  *
430  * Returns: #GRegex object used in @match_info
431  *
432  * Since: 2.14
433  */
434 GRegex *
435 g_match_info_get_regex (const GMatchInfo *match_info)
436 {
437   g_return_val_if_fail (match_info != NULL, NULL);
438   return match_info->regex;
439 }
440
441 /**
442  * g_match_info_get_string:
443  * @match_info: a #GMatchInfo
444  *
445  * Returns the string searched with @match_info. This is the
446  * string passed to g_regex_match() or g_regex_replace() so
447  * you may not free it before calling this function.
448  *
449  * Returns: the string searched with @match_info
450  *
451  * Since: 2.14
452  */
453 const gchar *
454 g_match_info_get_string (const GMatchInfo *match_info)
455 {
456   g_return_val_if_fail (match_info != NULL, NULL);
457   return match_info->string;
458 }
459
460 /**
461  * g_match_info_free:
462  * @match_info: a #GMatchInfo
463  *
464  * Frees all the memory associated with the #GMatchInfo structure.
465  *
466  * Since: 2.14
467  */
468 void
469 g_match_info_free (GMatchInfo *match_info)
470 {
471   if (match_info)
472     {
473       g_regex_unref (match_info->regex);
474       g_free (match_info->offsets);
475       g_free (match_info->workspace);
476       g_free (match_info);
477     }
478 }
479
480 /**
481  * g_match_info_next:
482  * @match_info: a #GMatchInfo structure
483  * @error: location to store the error occuring, or %NULL to ignore errors
484  *
485  * Scans for the next match using the same parameters of the previous
486  * call to g_regex_match_full() or g_regex_match() that returned
487  * @match_info.
488  *
489  * The match is done on the string passed to the match function, so you
490  * cannot free it before calling this function.
491  *
492  * Returns: %TRUE is the string matched, %FALSE otherwise
493  *
494  * Since: 2.14
495  */
496 gboolean
497 g_match_info_next (GMatchInfo  *match_info,
498                    GError     **error)
499 {
500   gint prev_match_start;
501   gint prev_match_end;
502
503   g_return_val_if_fail (match_info != NULL, FALSE);
504   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
505   g_return_val_if_fail (match_info->pos >= 0, FALSE);
506
507   prev_match_start = match_info->offsets[0];
508   prev_match_end = match_info->offsets[1];
509
510   match_info->matches = pcre_exec (match_info->regex->pcre_re,
511                                    match_info->regex->extra,
512                                    match_info->string,
513                                    match_info->string_len,
514                                    match_info->pos,
515                                    match_info->regex->match_opts | match_info->match_opts,
516                                    match_info->offsets,
517                                    match_info->n_offsets);
518   if (IS_PCRE_ERROR (match_info->matches))
519     {
520       g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
521                    _("Error while matching regular expression %s: %s"),
522                    match_info->regex->pattern, match_error (match_info->matches));
523       return FALSE;
524     }
525
526   /* avoid infinite loops if the pattern is an empty string or something
527    * equivalent */
528   if (match_info->pos == match_info->offsets[1])
529     {
530       if (match_info->pos > match_info->string_len)
531         {
532           /* we have reached the end of the string */
533           match_info->pos = -1;
534           match_info->matches = PCRE_ERROR_NOMATCH;
535           return FALSE;
536         }
537
538       match_info->pos = NEXT_CHAR (match_info->regex,
539                                    &match_info->string[match_info->pos]) -
540                                    match_info->string;
541     }
542   else
543     {
544       match_info->pos = match_info->offsets[1];
545     }
546
547   /* it's possible to get two identical matches when we are matching
548    * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
549    * the string is "RegExTest" we have:
550    *  - search at position 0: match from 0 to 0
551    *  - search at position 1: match from 3 to 3
552    *  - search at position 3: match from 3 to 3 (duplicate)
553    *  - search at position 4: match from 5 to 5
554    *  - search at position 5: match from 5 to 5 (duplicate)
555    *  - search at position 6: no match -> stop
556    * so we have to ignore the duplicates.
557    * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
558   if (match_info->matches >= 0 &&
559       prev_match_start == match_info->offsets[0] &&
560       prev_match_end == match_info->offsets[1])
561     {
562       /* ignore this match and search the next one */
563       return g_match_info_next (match_info, error);
564     }
565
566   return match_info->matches >= 0;
567 }
568
569 /**
570  * g_match_info_matches:
571  * @match_info: a #GMatchInfo structure
572  *
573  * Returns whether the previous match operation succeeded.
574  * 
575  * Returns: %TRUE if the previous match operation succeeded, 
576  *   %FALSE otherwise
577  *
578  * Since: 2.14
579  */
580 gboolean
581 g_match_info_matches (const GMatchInfo *match_info)
582 {
583   g_return_val_if_fail (match_info != NULL, FALSE);
584
585   return match_info->matches >= 0;
586 }
587
588 /**
589  * g_match_info_get_match_count:
590  * @match_info: a #GMatchInfo structure
591  *
592  * Retrieves the number of matched substrings (including substring 0, 
593  * that is the whole matched text), so 1 is returned if the pattern 
594  * has no substrings in it and 0 is returned if the match failed.
595  *
596  * If the last match was obtained using the DFA algorithm, that is 
597  * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
598  * count is not that of the number of capturing parentheses but that of
599  * the number of matched substrings.
600  *
601  * Returns: Number of matched substrings, or -1 if an error occurred
602  *
603  * Since: 2.14
604  */
605 gint
606 g_match_info_get_match_count (const GMatchInfo *match_info)
607 {
608   g_return_val_if_fail (match_info, -1);
609
610   if (match_info->matches == PCRE_ERROR_NOMATCH)
611     /* no match */
612     return 0;
613   else if (match_info->matches < PCRE_ERROR_NOMATCH)
614     /* error */
615     return -1;
616   else
617     /* match */
618     return match_info->matches;
619 }
620
621 /**
622  * g_match_info_is_partial_match:
623  * @match_info: a #GMatchInfo structure
624  *
625  * Usually if the string passed to g_regex_match*() matches as far as
626  * it goes, but is too short to match the entire pattern, %FALSE is
627  * returned. There are circumstances where it might be helpful to
628  * distinguish this case from other cases in which there is no match.
629  *
630  * Consider, for example, an application where a human is required to
631  * type in data for a field with specific formatting requirements. An
632  * example might be a date in the form ddmmmyy, defined by the pattern
633  * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
634  * If the application sees the user’s keystrokes one by one, and can
635  * check that what has been typed so far is potentially valid, it is
636  * able to raise an error as soon as a mistake is made.
637  *
638  * GRegex supports the concept of partial matching by means of the
639  * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
640  * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
641  * for a complete match, %FALSE otherwise. But, when these functions
642  * return %FALSE, you can check if the match was partial calling
643  * g_match_info_is_partial_match().
644  *
645  * When using partial matching you cannot use g_match_info_fetch*().
646  *
647  * Because of the way certain internal optimizations are implemented 
648  * the partial matching algorithm cannot be used with all patterns. 
649  * So repeated single characters such as "a{2,4}" and repeated single 
650  * meta-sequences such as "\d+" are not permitted if the maximum number 
651  * of occurrences is greater than one. Optional items such as "\d?" 
652  * (where the maximum is one) are permitted. Quantifiers with any values 
653  * are permitted after parentheses, so the invalid examples above can be 
654  * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set 
655  * for a pattern that does not conform to the restrictions, matching 
656  * functions return an error.
657  *
658  * Returns: %TRUE if the match was partial, %FALSE otherwise
659  *
660  * Since: 2.14
661  */
662 gboolean
663 g_match_info_is_partial_match (const GMatchInfo *match_info)
664 {
665   g_return_val_if_fail (match_info != NULL, FALSE);
666
667   return match_info->matches == PCRE_ERROR_PARTIAL;
668 }
669
670 /**
671  * g_match_info_expand_references:
672  * @match_info: a #GMatchInfo or %NULL
673  * @string_to_expand: the string to expand
674  * @error: location to store the error occuring, or %NULL to ignore errors
675  *
676  * Returns a new string containing the text in @string_to_expand with
677  * references and escape sequences expanded. References refer to the last
678  * match done with @string against @regex and have the same syntax used by
679  * g_regex_replace().
680  *
681  * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
682  * passed to g_regex_new().
683  *
684  * The backreferences are extracted from the string passed to the match
685  * function, so you cannot call this function after freeing the string.
686  *
687  * @match_info may be %NULL in which case @string_to_expand must not
688  * contain references. For instance "foo\n" does not refer to an actual
689  * pattern and '\n' merely will be replaced with \n character,
690  * while to expand "\0" (whole match) one needs the result of a match.
691  * Use g_regex_check_replacement() to find out whether @string_to_expand
692  * contains references.
693  *
694  * Returns: (allow-none): the expanded string, or %NULL if an error occurred
695  *
696  * Since: 2.14
697  */
698 gchar *
699 g_match_info_expand_references (const GMatchInfo  *match_info, 
700                                 const gchar       *string_to_expand,
701                                 GError           **error)
702 {
703   GString *result;
704   GList *list;
705   GError *tmp_error = NULL;
706
707   g_return_val_if_fail (string_to_expand != NULL, NULL);
708   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
709
710   list = split_replacement (string_to_expand, &tmp_error);
711   if (tmp_error != NULL)
712     {
713       g_propagate_error (error, tmp_error);
714       return NULL;
715     }
716
717   if (!match_info && interpolation_list_needs_match (list))
718     {
719       g_critical ("String '%s' contains references to the match, can't "
720                   "expand references without GMatchInfo object",
721                   string_to_expand);
722       return NULL;
723     }
724
725   result = g_string_sized_new (strlen (string_to_expand));
726   interpolate_replacement (match_info, result, list);
727
728   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
729   g_list_free (list);
730
731   return g_string_free (result, FALSE);
732 }
733
734 /**
735  * g_match_info_fetch:
736  * @match_info: #GMatchInfo structure
737  * @match_num: number of the sub expression
738  *
739  * Retrieves the text matching the @match_num<!-- -->'th capturing 
740  * parentheses. 0 is the full text of the match, 1 is the first paren 
741  * set, 2 the second, and so on.
742  *
743  * If @match_num is a valid sub pattern but it didn't match anything 
744  * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty 
745  * string is returned.
746  *
747  * If the match was obtained using the DFA algorithm, that is using
748  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
749  * string is not that of a set of parentheses but that of a matched
750  * substring. Substrings are matched in reverse order of length, so 
751  * 0 is the longest match.
752  *
753  * The string is fetched from the string passed to the match function,
754  * so you cannot call this function after freeing the string.
755  *
756  * Returns: (allow-none): The matched substring, or %NULL if an error
757  *     occurred. You have to free the string yourself
758  *
759  * Since: 2.14
760  */
761 gchar *
762 g_match_info_fetch (const GMatchInfo *match_info,
763                     gint              match_num)
764 {
765   /* we cannot use pcre_get_substring() because it allocates the
766    * string using pcre_malloc(). */
767   gchar *match = NULL;
768   gint start, end;
769
770   g_return_val_if_fail (match_info != NULL, NULL);
771   g_return_val_if_fail (match_num >= 0, NULL);
772
773   /* match_num does not exist or it didn't matched, i.e. matching "b"
774    * against "(a)?b" then group 0 is empty. */
775   if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
776     match = NULL;
777   else if (start == -1)
778     match = g_strdup ("");
779   else
780     match = g_strndup (&match_info->string[start], end - start);
781
782   return match;
783 }
784
785 /**
786  * g_match_info_fetch_pos:
787  * @match_info: #GMatchInfo structure
788  * @match_num: number of the sub expression
789  * @start_pos: (out) (allow-none): pointer to location where to store
790  *     the start position, or %NULL
791  * @end_pos: (out) (allow-none): pointer to location where to store
792  *     the end position, or %NULL
793  *
794  * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
795  * parentheses. 0 is the full text of the match, 1 is the first
796  * paren set, 2 the second, and so on.
797  *
798  * If @match_num is a valid sub pattern but it didn't match anything
799  * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
800  * and @end_pos are set to -1 and %TRUE is returned.
801  *
802  * If the match was obtained using the DFA algorithm, that is using
803  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
804  * position is not that of a set of parentheses but that of a matched
805  * substring. Substrings are matched in reverse order of length, so
806  * 0 is the longest match.
807  *
808  * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
809  *   the position cannot be fetched, @start_pos and @end_pos are left
810  *   unchanged
811  *
812  * Since: 2.14
813  */
814 gboolean
815 g_match_info_fetch_pos (const GMatchInfo *match_info,
816                         gint              match_num,
817                         gint             *start_pos,
818                         gint             *end_pos)
819 {
820   g_return_val_if_fail (match_info != NULL, FALSE);
821   g_return_val_if_fail (match_num >= 0, FALSE);
822  
823   /* make sure the sub expression number they're requesting is less than
824    * the total number of sub expressions that were matched. */
825   if (match_num >= match_info->matches)
826     return FALSE;
827
828   if (start_pos != NULL)
829     *start_pos = match_info->offsets[2 * match_num];
830
831   if (end_pos != NULL)
832     *end_pos = match_info->offsets[2 * match_num + 1];
833
834   return TRUE;
835 }
836
837 /*
838  * Returns number of first matched subpattern with name @name.
839  * There may be more than one in case when DUPNAMES is used,
840  * and not all subpatterns with that name match;
841  * pcre_get_stringnumber() does not work in that case.
842  */
843 static gint
844 get_matched_substring_number (const GMatchInfo *match_info,
845                               const gchar      *name)
846 {
847   gint entrysize;
848   gchar *first, *last;
849   guchar *entry;
850
851   if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
852     return pcre_get_stringnumber (match_info->regex->pcre_re, name);
853
854   /* This code is copied from pcre_get.c: get_first_set() */
855   entrysize = pcre_get_stringtable_entries (match_info->regex->pcre_re, 
856                                             name,
857                                             &first,
858                                             &last);
859
860   if (entrysize <= 0)
861     return entrysize;
862
863   for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
864     {
865       gint n = (entry[0] << 8) + entry[1];
866       if (match_info->offsets[n*2] >= 0)
867         return n;
868     }
869
870   return (first[0] << 8) + first[1];
871 }
872
873 /**
874  * g_match_info_fetch_named:
875  * @match_info: #GMatchInfo structure
876  * @name: name of the subexpression
877  *
878  * Retrieves the text matching the capturing parentheses named @name.
879  *
880  * If @name is a valid sub pattern name but it didn't match anything 
881  * (e.g. sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b") 
882  * then an empty string is returned.
883  *
884  * The string is fetched from the string passed to the match function,
885  * so you cannot call this function after freeing the string.
886  *
887  * Returns: (allow-none): The matched substring, or %NULL if an error
888  *     occurred. You have to free the string yourself
889  *
890  * Since: 2.14
891  */
892 gchar *
893 g_match_info_fetch_named (const GMatchInfo *match_info,
894                           const gchar      *name)
895 {
896   /* we cannot use pcre_get_named_substring() because it allocates the
897    * string using pcre_malloc(). */
898   gint num;
899
900   g_return_val_if_fail (match_info != NULL, NULL);
901   g_return_val_if_fail (name != NULL, NULL);
902
903   num = get_matched_substring_number (match_info, name);
904   if (num < 0)
905     return NULL;
906   else
907     return g_match_info_fetch (match_info, num);
908 }
909
910 /**
911  * g_match_info_fetch_named_pos:
912  * @match_info: #GMatchInfo structure
913  * @name: name of the subexpression
914  * @start_pos: (out) (allow-none): pointer to location where to store
915  *     the start position, or %NULL
916  * @end_pos: (out) (allow-none): pointer to location where to store
917  *     the end position, or %NULL
918  *
919  * Retrieves the position in bytes of the capturing parentheses named @name.
920  *
921  * If @name is a valid sub pattern name but it didn't match anything
922  * (e.g. sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b")
923  * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
924  *
925  * Returns: %TRUE if the position was fetched, %FALSE otherwise.
926  *     If the position cannot be fetched, @start_pos and @end_pos
927  *     are left unchanged.
928  *
929  * Since: 2.14
930  */
931 gboolean
932 g_match_info_fetch_named_pos (const GMatchInfo *match_info,
933                               const gchar      *name,
934                               gint             *start_pos,
935                               gint             *end_pos)
936 {
937   gint num;
938
939   g_return_val_if_fail (match_info != NULL, FALSE);
940   g_return_val_if_fail (name != NULL, FALSE);
941
942   num = get_matched_substring_number (match_info, name);
943   if (num < 0)
944     return FALSE;
945
946   return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
947 }
948
949 /**
950  * g_match_info_fetch_all:
951  * @match_info: a #GMatchInfo structure
952  *
953  * Bundles up pointers to each of the matching substrings from a match
954  * and stores them in an array of gchar pointers. The first element in
955  * the returned array is the match number 0, i.e. the entire matched
956  * text.
957  *
958  * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
959  * "b" against "(a)?b") then an empty string is inserted.
960  *
961  * If the last match was obtained using the DFA algorithm, that is using
962  * g_regex_match_all() or g_regex_match_all_full(), the retrieved
963  * strings are not that matched by sets of parentheses but that of the
964  * matched substring. Substrings are matched in reverse order of length,
965  * so the first one is the longest match.
966  *
967  * The strings are fetched from the string passed to the match function,
968  * so you cannot call this function after freeing the string.
969  *
970  * Returns: (allow-none): a %NULL-terminated array of gchar * pointers.
971  *     It must be freed using g_strfreev(). If the previous match failed
972  *     %NULL is returned
973  *
974  * Since: 2.14
975  */
976 gchar **
977 g_match_info_fetch_all (const GMatchInfo *match_info)
978 {
979   /* we cannot use pcre_get_substring_list() because the returned value
980    * isn't suitable for g_strfreev(). */
981   gchar **result;
982   gint i;
983
984   g_return_val_if_fail (match_info != NULL, NULL);
985
986   if (match_info->matches < 0)
987     return NULL;
988
989   result = g_new (gchar *, match_info->matches + 1);
990   for (i = 0; i < match_info->matches; i++)
991     result[i] = g_match_info_fetch (match_info, i);
992   result[i] = NULL;
993
994   return result;
995 }
996
997
998 /* GRegex */
999
1000 GQuark
1001 g_regex_error_quark (void)
1002 {
1003   static GQuark error_quark = 0;
1004
1005   if (error_quark == 0)
1006     error_quark = g_quark_from_static_string ("g-regex-error-quark");
1007
1008   return error_quark;
1009 }
1010
1011 /**
1012  * g_regex_ref:
1013  * @regex: a #GRegex
1014  *
1015  * Increases reference count of @regex by 1.
1016  *
1017  * Returns: @regex
1018  *
1019  * Since: 2.14
1020  */
1021 GRegex *
1022 g_regex_ref (GRegex *regex)
1023 {
1024   g_return_val_if_fail (regex != NULL, NULL);
1025   g_atomic_int_inc (&regex->ref_count);
1026   return regex;
1027 }
1028
1029 /**
1030  * g_regex_unref:
1031  * @regex: a #GRegex
1032  *
1033  * Decreases reference count of @regex by 1. When reference count drops
1034  * to zero, it frees all the memory associated with the regex structure.
1035  *
1036  * Since: 2.14
1037  */
1038 void
1039 g_regex_unref (GRegex *regex)
1040 {
1041   g_return_if_fail (regex != NULL);
1042
1043   if (g_atomic_int_exchange_and_add (&regex->ref_count, -1) - 1 == 0)
1044     {
1045       g_free (regex->pattern);
1046       if (regex->pcre_re != NULL)
1047         pcre_free (regex->pcre_re);
1048       if (regex->extra != NULL)
1049         pcre_free (regex->extra);
1050       g_free (regex);
1051     }
1052 }
1053
1054 /** 
1055  * g_regex_new:
1056  * @pattern: the regular expression
1057  * @compile_options: compile options for the regular expression, or 0 
1058  * @match_options: match options for the regular expression, or 0
1059  * @error: return location for a #GError
1060  * 
1061  * Compiles the regular expression to an internal form, and does 
1062  * the initial setup of the #GRegex structure.  
1063  * 
1064  * Returns: a #GRegex structure. Call g_regex_unref() when you 
1065  *   are done with it
1066  *
1067  * Since: 2.14
1068  */
1069 GRegex *
1070 g_regex_new (const gchar         *pattern, 
1071              GRegexCompileFlags   compile_options,
1072              GRegexMatchFlags     match_options,
1073              GError             **error)
1074 {
1075   GRegex *regex;
1076   pcre *re;
1077   const gchar *errmsg;
1078   gint erroffset;
1079   gint errcode;
1080   gboolean optimize = FALSE;
1081   static gboolean initialized = FALSE;
1082   unsigned long int pcre_compile_options;
1083
1084   g_return_val_if_fail (pattern != NULL, NULL);
1085   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1086   g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
1087   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1088
1089   if (!initialized)
1090     {
1091       gint support;
1092       const gchar *msg;
1093
1094       pcre_config (PCRE_CONFIG_UTF8, &support);
1095       if (!support)
1096         {
1097           msg = N_("PCRE library is compiled without UTF8 support");
1098           g_critical ("%s", msg);
1099           g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1100           return NULL;
1101         }
1102
1103       pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
1104       if (!support)
1105         {
1106           msg = N_("PCRE library is compiled without UTF8 properties support");
1107           g_critical ("%s", msg);
1108           g_set_error_literal (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, gettext (msg));
1109           return NULL;
1110         }
1111
1112       initialized = TRUE;
1113     }
1114
1115   /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1116    * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1117   if (compile_options & G_REGEX_OPTIMIZE)
1118     optimize = TRUE;
1119
1120   /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1121    * instead uses UTF-8 only if required with PCRE_UTF8. */
1122   if (compile_options & G_REGEX_RAW)
1123     {
1124       /* disable utf-8 */
1125       compile_options &= ~G_REGEX_RAW;
1126     }
1127   else
1128     {
1129       /* enable utf-8 */
1130       compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
1131       match_options |= PCRE_NO_UTF8_CHECK;
1132     }
1133
1134   /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1135    * not for the system one. */
1136   if (!(compile_options & G_REGEX_NEWLINE_CR) &&
1137       !(compile_options & G_REGEX_NEWLINE_LF))
1138     {
1139       compile_options |= PCRE_NEWLINE_ANY;
1140     }
1141
1142   /* compile the pattern */
1143   re = pcre_compile2 (pattern, compile_options, &errcode,
1144                       &errmsg, &erroffset, NULL);
1145
1146   /* if the compilation failed, set the error member and return 
1147    * immediately */
1148   if (re == NULL)
1149     {
1150       GError *tmp_error;
1151
1152       /* Translate the PCRE error code to GRegexError and use a translated
1153        * error message if possible */
1154       translate_compile_error (&errcode, &errmsg);
1155
1156       /* PCRE uses byte offsets but we want to show character offsets */
1157       erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
1158
1159       tmp_error = g_error_new (G_REGEX_ERROR, errcode,
1160                                _("Error while compiling regular "
1161                                  "expression %s at char %d: %s"),
1162                                pattern, erroffset, errmsg);
1163       g_propagate_error (error, tmp_error);
1164
1165       return NULL;
1166     }
1167
1168   /* For options set at the beginning of the pattern, pcre puts them into
1169    * compile options, e.g. "(?i)foo" will make the pcre structure store
1170    * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1171   pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
1172   compile_options = pcre_compile_options;
1173
1174   if (!(compile_options & G_REGEX_DUPNAMES))
1175     {
1176       gboolean jchanged = FALSE;
1177       pcre_fullinfo (re, NULL, PCRE_INFO_JCHANGED, &jchanged);
1178       if (jchanged)
1179         compile_options |= G_REGEX_DUPNAMES;
1180     }
1181
1182   regex = g_new0 (GRegex, 1);
1183   regex->ref_count = 1;
1184   regex->pattern = g_strdup (pattern);
1185   regex->pcre_re = re;
1186   regex->compile_opts = compile_options;
1187   regex->match_opts = match_options;
1188
1189   if (optimize)
1190     {
1191       regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
1192       if (errmsg != NULL)
1193         {
1194           GError *tmp_error = g_error_new (G_REGEX_ERROR,
1195                                            G_REGEX_ERROR_OPTIMIZE, 
1196                                            _("Error while optimizing "
1197                                              "regular expression %s: %s"),
1198                                            regex->pattern,
1199                                            errmsg);
1200           g_propagate_error (error, tmp_error);
1201
1202           g_regex_unref (regex);
1203           return NULL;
1204         }
1205     }
1206
1207   return regex;
1208 }
1209
1210 /**
1211  * g_regex_get_pattern:
1212  * @regex: a #GRegex structure
1213  *
1214  * Gets the pattern string associated with @regex, i.e. a copy of 
1215  * the string passed to g_regex_new().
1216  *
1217  * Returns: the pattern of @regex
1218  *
1219  * Since: 2.14
1220  */
1221 const gchar *
1222 g_regex_get_pattern (const GRegex *regex)
1223 {
1224   g_return_val_if_fail (regex != NULL, NULL);
1225
1226   return regex->pattern;
1227 }
1228
1229 /**
1230  * g_regex_get_max_backref:
1231  * @regex: a #GRegex
1232  *  
1233  * Returns the number of the highest back reference
1234  * in the pattern, or 0 if the pattern does not contain
1235  * back references.
1236  *
1237  * Returns: the number of the highest back reference
1238  *
1239  * Since: 2.14
1240  */
1241 gint
1242 g_regex_get_max_backref (const GRegex *regex)
1243 {
1244   gint value;
1245
1246   pcre_fullinfo (regex->pcre_re, regex->extra,
1247                  PCRE_INFO_BACKREFMAX, &value);
1248
1249   return value;
1250 }
1251
1252 /**
1253  * g_regex_get_capture_count:
1254  * @regex: a #GRegex
1255  *
1256  * Returns the number of capturing subpatterns in the pattern.
1257  *
1258  * Returns: the number of capturing subpatterns
1259  *
1260  * Since: 2.14
1261  */
1262 gint
1263 g_regex_get_capture_count (const GRegex *regex)
1264 {
1265   gint value;
1266
1267   pcre_fullinfo (regex->pcre_re, regex->extra,
1268                  PCRE_INFO_CAPTURECOUNT, &value);
1269
1270   return value;
1271 }
1272
1273 /**
1274  * g_regex_get_compile_flags:
1275  * @regex: a #GRegex
1276  *
1277  * Returns the compile options that @regex was created with.
1278  *
1279  * Returns: flags from #GRegexCompileFlags
1280  *
1281  * Since: 2.26
1282  */
1283 GRegexCompileFlags
1284 g_regex_get_compile_flags (const GRegex *regex)
1285 {
1286   g_return_val_if_fail (regex != NULL, 0);
1287
1288   return regex->compile_opts;
1289 }
1290
1291 /**
1292  * g_regex_get_match_flags:
1293  * @regex: a #GRegex
1294  *
1295  * Returns the match options that @regex was created with.
1296  *
1297  * Returns: flags from #GRegexMatchFlags
1298  *
1299  * Since: 2.26
1300  */
1301 GRegexMatchFlags
1302 g_regex_get_match_flags (const GRegex *regex)
1303 {
1304   g_return_val_if_fail (regex != NULL, 0);
1305
1306   return regex->match_opts;
1307 }
1308
1309 /**
1310  * g_regex_match_simple:
1311  * @pattern: the regular expression
1312  * @string: the string to scan for matches
1313  * @compile_options: compile options for the regular expression, or 0
1314  * @match_options: match options, or 0
1315  *
1316  * Scans for a match in @string for @pattern.
1317  *
1318  * This function is equivalent to g_regex_match() but it does not
1319  * require to compile the pattern with g_regex_new(), avoiding some
1320  * lines of code when you need just to do a match without extracting
1321  * substrings, capture counts, and so on.
1322  *
1323  * If this function is to be called on the same @pattern more than
1324  * once, it's more efficient to compile the pattern once with
1325  * g_regex_new() and then use g_regex_match().
1326  *
1327  * Returns: %TRUE if the string matched, %FALSE otherwise
1328  *
1329  * Since: 2.14
1330  */
1331 gboolean
1332 g_regex_match_simple (const gchar        *pattern, 
1333                       const gchar        *string, 
1334                       GRegexCompileFlags  compile_options,
1335                       GRegexMatchFlags    match_options)
1336 {
1337   GRegex *regex;
1338   gboolean result;
1339
1340   regex = g_regex_new (pattern, compile_options, 0, NULL);
1341   if (!regex)
1342     return FALSE;
1343   result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
1344   g_regex_unref (regex);
1345   return result;
1346 }
1347
1348 /**
1349  * g_regex_match:
1350  * @regex: a #GRegex structure from g_regex_new()
1351  * @string: the string to scan for matches
1352  * @match_options: match options
1353  * @match_info: (out) (allow-none): pointer to location where to store
1354  *     the #GMatchInfo, or %NULL if you do not need it
1355  *
1356  * Scans for a match in string for the pattern in @regex.
1357  * The @match_options are combined with the match options specified
1358  * when the @regex structure was created, letting you have more
1359  * flexibility in reusing #GRegex structures.
1360  *
1361  * A #GMatchInfo structure, used to get information on the match,
1362  * is stored in @match_info if not %NULL. Note that if @match_info
1363  * is not %NULL then it is created even if the function returns %FALSE,
1364  * i.e. you must free it regardless if regular expression actually matched.
1365  *
1366  * To retrieve all the non-overlapping matches of the pattern in
1367  * string you can use g_match_info_next().
1368  *
1369  * |[
1370  * static void
1371  * print_uppercase_words (const gchar *string)
1372  * {
1373  *   /&ast; Print all uppercase-only words. &ast;/
1374  *   GRegex *regex;
1375  *   GMatchInfo *match_info;
1376  *   &nbsp;
1377  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1378  *   g_regex_match (regex, string, 0, &amp;match_info);
1379  *   while (g_match_info_matches (match_info))
1380  *     {
1381  *       gchar *word = g_match_info_fetch (match_info, 0);
1382  *       g_print ("Found: %s\n", word);
1383  *       g_free (word);
1384  *       g_match_info_next (match_info, NULL);
1385  *     }
1386  *   g_match_info_free (match_info);
1387  *   g_regex_unref (regex);
1388  * }
1389  * ]|
1390  *
1391  * @string is not copied and is used in #GMatchInfo internally. If
1392  * you use any #GMatchInfo method (except g_match_info_free()) after
1393  * freeing or modifying @string then the behaviour is undefined.
1394  *
1395  * Returns: %TRUE is the string matched, %FALSE otherwise
1396  *
1397  * Since: 2.14
1398  */
1399 gboolean
1400 g_regex_match (const GRegex      *regex,
1401                const gchar       *string,
1402                GRegexMatchFlags   match_options,
1403                GMatchInfo       **match_info)
1404 {
1405   return g_regex_match_full (regex, string, -1, 0, match_options,
1406                              match_info, NULL);
1407 }
1408
1409 /**
1410  * g_regex_match_full:
1411  * @regex: a #GRegex structure from g_regex_new()
1412  * @string: (array length=string_len): the string to scan for matches
1413  * @string_len: the length of @string, or -1 if @string is nul-terminated
1414  * @start_position: starting index of the string to match
1415  * @match_options: match options
1416  * @match_info: (out) (allow-none): pointer to location where to store
1417  *     the #GMatchInfo, or %NULL if you do not need it
1418  * @error: location to store the error occuring, or %NULL to ignore errors
1419  *
1420  * Scans for a match in string for the pattern in @regex.
1421  * The @match_options are combined with the match options specified
1422  * when the @regex structure was created, letting you have more
1423  * flexibility in reusing #GRegex structures.
1424  *
1425  * Setting @start_position differs from just passing over a shortened
1426  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1427  * that begins with any kind of lookbehind assertion, such as "\b".
1428  *
1429  * A #GMatchInfo structure, used to get information on the match, is
1430  * stored in @match_info if not %NULL. Note that if @match_info is
1431  * not %NULL then it is created even if the function returns %FALSE,
1432  * i.e. you must free it regardless if regular expression actually
1433  * matched.
1434  *
1435  * @string is not copied and is used in #GMatchInfo internally. If
1436  * you use any #GMatchInfo method (except g_match_info_free()) after
1437  * freeing or modifying @string then the behaviour is undefined.
1438  *
1439  * To retrieve all the non-overlapping matches of the pattern in
1440  * string you can use g_match_info_next().
1441  *
1442  * |[
1443  * static void
1444  * print_uppercase_words (const gchar *string)
1445  * {
1446  *   /&ast; Print all uppercase-only words. &ast;/
1447  *   GRegex *regex;
1448  *   GMatchInfo *match_info;
1449  *   GError *error = NULL;
1450  *   &nbsp;
1451  *   regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1452  *   g_regex_match_full (regex, string, -1, 0, 0, &amp;match_info, &amp;error);
1453  *   while (g_match_info_matches (match_info))
1454  *     {
1455  *       gchar *word = g_match_info_fetch (match_info, 0);
1456  *       g_print ("Found: %s\n", word);
1457  *       g_free (word);
1458  *       g_match_info_next (match_info, &amp;error);
1459  *     }
1460  *   g_match_info_free (match_info);
1461  *   g_regex_unref (regex);
1462  *   if (error != NULL)
1463  *     {
1464  *       g_printerr ("Error while matching: %s\n", error->message);
1465  *       g_error_free (error);
1466  *     }
1467  * }
1468  * ]|
1469  *
1470  * Returns: %TRUE is the string matched, %FALSE otherwise
1471  *
1472  * Since: 2.14
1473  */
1474 gboolean
1475 g_regex_match_full (const GRegex      *regex,
1476                     const gchar       *string,
1477                     gssize             string_len,
1478                     gint               start_position,
1479                     GRegexMatchFlags   match_options,
1480                     GMatchInfo       **match_info,
1481                     GError           **error)
1482 {
1483   GMatchInfo *info;
1484   gboolean match_ok;
1485
1486   g_return_val_if_fail (regex != NULL, FALSE);
1487   g_return_val_if_fail (string != NULL, FALSE);
1488   g_return_val_if_fail (start_position >= 0, FALSE);
1489   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1490   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1491
1492   info = match_info_new (regex, string, string_len, start_position,
1493                          match_options, FALSE);
1494   match_ok = g_match_info_next (info, error);
1495   if (match_info != NULL)
1496     *match_info = info;
1497   else
1498     g_match_info_free (info);
1499
1500   return match_ok;
1501 }
1502
1503 /**
1504  * g_regex_match_all:
1505  * @regex: a #GRegex structure from g_regex_new()
1506  * @string: the string to scan for matches
1507  * @match_options: match options
1508  * @match_info: (out) (allow-none): pointer to location where to store
1509  *     the #GMatchInfo, or %NULL if you do not need it
1510  *
1511  * Using the standard algorithm for regular expression matching only
1512  * the longest match in the string is retrieved. This function uses
1513  * a different algorithm so it can retrieve all the possible matches.
1514  * For more documentation see g_regex_match_all_full().
1515  *
1516  * A #GMatchInfo structure, used to get information on the match, is
1517  * stored in @match_info if not %NULL. Note that if @match_info is
1518  * not %NULL then it is created even if the function returns %FALSE,
1519  * i.e. you must free it regardless if regular expression actually
1520  * matched.
1521  *
1522  * @string is not copied and is used in #GMatchInfo internally. If
1523  * you use any #GMatchInfo method (except g_match_info_free()) after
1524  * freeing or modifying @string then the behaviour is undefined.
1525  *
1526  * Returns: %TRUE is the string matched, %FALSE otherwise
1527  *
1528  * Since: 2.14
1529  */
1530 gboolean
1531 g_regex_match_all (const GRegex      *regex,
1532                    const gchar       *string,
1533                    GRegexMatchFlags   match_options,
1534                    GMatchInfo       **match_info)
1535 {
1536   return g_regex_match_all_full (regex, string, -1, 0, match_options,
1537                                  match_info, NULL);
1538 }
1539
1540 /**
1541  * g_regex_match_all_full:
1542  * @regex: a #GRegex structure from g_regex_new()
1543  * @string: (array length=string_len): the string to scan for matches
1544  * @string_len: the length of @string, or -1 if @string is nul-terminated
1545  * @start_position: starting index of the string to match
1546  * @match_options: match options
1547  * @match_info: (out) (allow-none): pointer to location where to store
1548  *     the #GMatchInfo, or %NULL if you do not need it
1549  * @error: location to store the error occuring, or %NULL to ignore errors
1550  *
1551  * Using the standard algorithm for regular expression matching only
1552  * the longest match in the string is retrieved, it is not possibile
1553  * to obtain all the available matches. For instance matching
1554  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;"
1555  * you get "&lt;a&gt; &lt;b&gt; &lt;c&gt;".
1556  *
1557  * This function uses a different algorithm (called DFA, i.e. deterministic
1558  * finite automaton), so it can retrieve all the possible matches, all
1559  * starting at the same point in the string. For instance matching
1560  * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;"
1561  * you would obtain three matches: "&lt;a&gt; &lt;b&gt; &lt;c&gt;",
1562  * "&lt;a&gt; &lt;b&gt;" and "&lt;a&gt;".
1563  *
1564  * The number of matched strings is retrieved using
1565  * g_match_info_get_match_count(). To obtain the matched strings and
1566  * their position you can use, respectively, g_match_info_fetch() and
1567  * g_match_info_fetch_pos(). Note that the strings are returned in
1568  * reverse order of length; that is, the longest matching string is
1569  * given first.
1570  *
1571  * Note that the DFA algorithm is slower than the standard one and it
1572  * is not able to capture substrings, so backreferences do not work.
1573  *
1574  * Setting @start_position differs from just passing over a shortened
1575  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1576  * that begins with any kind of lookbehind assertion, such as "\b".
1577  *
1578  * A #GMatchInfo structure, used to get information on the match, is
1579  * stored in @match_info if not %NULL. Note that if @match_info is
1580  * not %NULL then it is created even if the function returns %FALSE,
1581  * i.e. you must free it regardless if regular expression actually
1582  * matched.
1583  *
1584  * @string is not copied and is used in #GMatchInfo internally. If
1585  * you use any #GMatchInfo method (except g_match_info_free()) after
1586  * freeing or modifying @string then the behaviour is undefined.
1587  *
1588  * Returns: %TRUE is the string matched, %FALSE otherwise
1589  *
1590  * Since: 2.14
1591  */
1592 gboolean
1593 g_regex_match_all_full (const GRegex      *regex,
1594                         const gchar       *string,
1595                         gssize             string_len,
1596                         gint               start_position,
1597                         GRegexMatchFlags   match_options,
1598                         GMatchInfo       **match_info,
1599                         GError           **error)
1600 {
1601   GMatchInfo *info;
1602   gboolean done;
1603
1604   g_return_val_if_fail (regex != NULL, FALSE);
1605   g_return_val_if_fail (string != NULL, FALSE);
1606   g_return_val_if_fail (start_position >= 0, FALSE);
1607   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1608   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
1609
1610   info = match_info_new (regex, string, string_len, start_position,
1611                          match_options, TRUE);
1612
1613   done = FALSE;
1614   while (!done)
1615     {
1616       done = TRUE;
1617       info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
1618                                      info->string, info->string_len,
1619                                      info->pos,
1620                                      regex->match_opts | match_options,
1621                                      info->offsets, info->n_offsets,
1622                                      info->workspace, info->n_workspace);
1623       if (info->matches == PCRE_ERROR_DFA_WSSIZE)
1624         {
1625           /* info->workspace is too small. */
1626           info->n_workspace *= 2;
1627           info->workspace = g_realloc (info->workspace,
1628                                        info->n_workspace * sizeof (gint));
1629           done = FALSE;
1630         }
1631       else if (info->matches == 0)
1632         {
1633           /* info->offsets is too small. */
1634           info->n_offsets *= 2;
1635           info->offsets = g_realloc (info->offsets,
1636                                      info->n_offsets * sizeof (gint));
1637           done = FALSE;
1638         }
1639       else if (IS_PCRE_ERROR (info->matches))
1640         {
1641           g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
1642                        _("Error while matching regular expression %s: %s"),
1643                        regex->pattern, match_error (info->matches));
1644         }
1645     }
1646
1647   /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1648   info->pos = -1;
1649
1650   if (match_info != NULL)
1651     *match_info = info;
1652   else
1653     g_match_info_free (info);
1654
1655   return info->matches >= 0;
1656 }
1657
1658 /**
1659  * g_regex_get_string_number:
1660  * @regex: #GRegex structure
1661  * @name: name of the subexpression
1662  *
1663  * Retrieves the number of the subexpression named @name.
1664  *
1665  * Returns: The number of the subexpression or -1 if @name 
1666  *   does not exists
1667  *
1668  * Since: 2.14
1669  */
1670 gint
1671 g_regex_get_string_number (const GRegex *regex,
1672                            const gchar  *name)
1673 {
1674   gint num;
1675
1676   g_return_val_if_fail (regex != NULL, -1);
1677   g_return_val_if_fail (name != NULL, -1);
1678
1679   num = pcre_get_stringnumber (regex->pcre_re, name);
1680   if (num == PCRE_ERROR_NOSUBSTRING)
1681     num = -1;
1682
1683   return num;
1684 }
1685
1686 /**
1687  * g_regex_split_simple:
1688  * @pattern: the regular expression
1689  * @string: the string to scan for matches
1690  * @compile_options: compile options for the regular expression, or 0
1691  * @match_options: match options, or 0
1692  *
1693  * Breaks the string on the pattern, and returns an array of 
1694  * the tokens. If the pattern contains capturing parentheses, 
1695  * then the text for each of the substrings will also be returned. 
1696  * If the pattern does not match anywhere in the string, then the 
1697  * whole string is returned as the first token.
1698  *
1699  * This function is equivalent to g_regex_split() but it does 
1700  * not require to compile the pattern with g_regex_new(), avoiding 
1701  * some lines of code when you need just to do a split without 
1702  * extracting substrings, capture counts, and so on.
1703  *
1704  * If this function is to be called on the same @pattern more than
1705  * once, it's more efficient to compile the pattern once with
1706  * g_regex_new() and then use g_regex_split().
1707  *
1708  * As a special case, the result of splitting the empty string "" 
1709  * is an empty vector, not a vector containing a single string. 
1710  * The reason for this special case is that being able to represent 
1711  * a empty vector is typically more useful than consistent handling 
1712  * of empty elements. If you do need to represent empty elements, 
1713  * you'll need to check for the empty string before calling this 
1714  * function.
1715  *
1716  * A pattern that can match empty strings splits @string into 
1717  * separate characters wherever it matches the empty string between 
1718  * characters. For example splitting "ab c" using as a separator 
1719  * "\s*", you will get "a", "b" and "c".
1720  *
1721  * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
1722  *
1723  * Since: 2.14
1724  **/
1725 gchar **
1726 g_regex_split_simple (const gchar        *pattern,
1727                       const gchar        *string, 
1728                       GRegexCompileFlags  compile_options,
1729                       GRegexMatchFlags    match_options)
1730 {
1731   GRegex *regex;
1732   gchar **result;
1733
1734   regex = g_regex_new (pattern, compile_options, 0, NULL);
1735   if (!regex)
1736     return NULL;
1737   result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
1738   g_regex_unref (regex);
1739   return result;
1740 }
1741
1742 /**
1743  * g_regex_split:
1744  * @regex: a #GRegex structure
1745  * @string: the string to split with the pattern
1746  * @match_options: match time option flags
1747  *
1748  * Breaks the string on the pattern, and returns an array of the tokens.
1749  * If the pattern contains capturing parentheses, then the text for each
1750  * of the substrings will also be returned. If the pattern does not match
1751  * anywhere in the string, then the whole string is returned as the first
1752  * token.
1753  *
1754  * As a special case, the result of splitting the empty string "" is an
1755  * empty vector, not a vector containing a single string. The reason for
1756  * this special case is that being able to represent a empty vector is
1757  * typically more useful than consistent handling of empty elements. If
1758  * you do need to represent empty elements, you'll need to check for the
1759  * empty string before calling this function.
1760  *
1761  * A pattern that can match empty strings splits @string into separate
1762  * characters wherever it matches the empty string between characters.
1763  * For example splitting "ab c" using as a separator "\s*", you will get
1764  * "a", "b" and "c".
1765  *
1766  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1767  *
1768  * Since: 2.14
1769  **/
1770 gchar **
1771 g_regex_split (const GRegex     *regex, 
1772                const gchar      *string, 
1773                GRegexMatchFlags  match_options)
1774 {
1775   return g_regex_split_full (regex, string, -1, 0,
1776                              match_options, 0, NULL);
1777 }
1778
1779 /**
1780  * g_regex_split_full:
1781  * @regex: a #GRegex structure
1782  * @string: (array length=string_len): the string to split with the pattern
1783  * @string_len: the length of @string, or -1 if @string is nul-terminated
1784  * @start_position: starting index of the string to match
1785  * @match_options: match time option flags
1786  * @max_tokens: the maximum number of tokens to split @string into.
1787  *   If this is less than 1, the string is split completely
1788  * @error: return location for a #GError
1789  *
1790  * Breaks the string on the pattern, and returns an array of the tokens.
1791  * If the pattern contains capturing parentheses, then the text for each
1792  * of the substrings will also be returned. If the pattern does not match
1793  * anywhere in the string, then the whole string is returned as the first
1794  * token.
1795  *
1796  * As a special case, the result of splitting the empty string "" is an
1797  * empty vector, not a vector containing a single string. The reason for
1798  * this special case is that being able to represent a empty vector is
1799  * typically more useful than consistent handling of empty elements. If
1800  * you do need to represent empty elements, you'll need to check for the
1801  * empty string before calling this function.
1802  *
1803  * A pattern that can match empty strings splits @string into separate
1804  * characters wherever it matches the empty string between characters.
1805  * For example splitting "ab c" using as a separator "\s*", you will get
1806  * "a", "b" and "c".
1807  *
1808  * Setting @start_position differs from just passing over a shortened 
1809  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
1810  * that begins with any kind of lookbehind assertion, such as "\b".
1811  *
1812  * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
1813  *
1814  * Since: 2.14
1815  **/
1816 gchar **
1817 g_regex_split_full (const GRegex      *regex,
1818                     const gchar       *string,
1819                     gssize             string_len,
1820                     gint               start_position,
1821                     GRegexMatchFlags   match_options,
1822                     gint               max_tokens,
1823                     GError           **error)
1824 {
1825   GError *tmp_error = NULL;
1826   GMatchInfo *match_info;
1827   GList *list, *last;
1828   gint i;
1829   gint token_count;
1830   gboolean match_ok;
1831   /* position of the last separator. */
1832   gint last_separator_end;
1833   /* was the last match 0 bytes long? */
1834   gboolean last_match_is_empty;
1835   /* the returned array of char **s */
1836   gchar **string_list;
1837
1838   g_return_val_if_fail (regex != NULL, NULL);
1839   g_return_val_if_fail (string != NULL, NULL);
1840   g_return_val_if_fail (start_position >= 0, NULL);
1841   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1842   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
1843
1844   if (max_tokens <= 0)
1845     max_tokens = G_MAXINT;
1846
1847   if (string_len < 0)
1848     string_len = strlen (string);
1849
1850   /* zero-length string */
1851   if (string_len - start_position == 0)
1852     return g_new0 (gchar *, 1);
1853
1854   if (max_tokens == 1)
1855     {
1856       string_list = g_new0 (gchar *, 2);
1857       string_list[0] = g_strndup (&string[start_position],
1858                                   string_len - start_position);
1859       return string_list;
1860     }
1861
1862   list = NULL;
1863   token_count = 0;
1864   last_separator_end = start_position;
1865   last_match_is_empty = FALSE;
1866
1867   match_ok = g_regex_match_full (regex, string, string_len, start_position,
1868                                  match_options, &match_info, &tmp_error);
1869   while (tmp_error == NULL)
1870     {
1871       if (match_ok)
1872         {
1873           last_match_is_empty =
1874                     (match_info->offsets[0] == match_info->offsets[1]);
1875
1876           /* we need to skip empty separators at the same position of the end
1877            * of another separator. e.g. the string is "a b" and the separator
1878            * is " *", so from 1 to 2 we have a match and at position 2 we have
1879            * an empty match. */
1880           if (last_separator_end != match_info->offsets[1])
1881             {
1882               gchar *token;
1883               gint match_count;
1884
1885               token = g_strndup (string + last_separator_end,
1886                                  match_info->offsets[0] - last_separator_end);
1887               list = g_list_prepend (list, token);
1888               token_count++;
1889
1890               /* if there were substrings, these need to be added to
1891                * the list. */
1892               match_count = g_match_info_get_match_count (match_info);
1893               if (match_count > 1)
1894                 {
1895                   for (i = 1; i < match_count; i++)
1896                     list = g_list_prepend (list, g_match_info_fetch (match_info, i));
1897                 }
1898             }
1899         }
1900       else
1901         {
1902           /* if there was no match, copy to end of string. */
1903           if (!last_match_is_empty)
1904             {
1905               gchar *token = g_strndup (string + last_separator_end,
1906                                         match_info->string_len - last_separator_end);
1907               list = g_list_prepend (list, token);
1908             }
1909           /* no more tokens, end the loop. */
1910           break;
1911         }
1912
1913       /* -1 to leave room for the last part. */
1914       if (token_count >= max_tokens - 1)
1915         {
1916           /* we have reached the maximum number of tokens, so we copy
1917            * the remaining part of the string. */
1918           if (last_match_is_empty)
1919             {
1920               /* the last match was empty, so we have moved one char
1921                * after the real position to avoid empty matches at the
1922                * same position. */
1923               match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
1924             }
1925           /* the if is needed in the case we have terminated the available
1926            * tokens, but we are at the end of the string, so there are no
1927            * characters left to copy. */
1928           if (string_len > match_info->pos)
1929             {
1930               gchar *token = g_strndup (string + match_info->pos,
1931                                         string_len - match_info->pos);
1932               list = g_list_prepend (list, token);
1933             }
1934           /* end the loop. */
1935           break;
1936         }
1937
1938       last_separator_end = match_info->pos;
1939       if (last_match_is_empty)
1940         /* if the last match was empty, g_match_info_next() has moved
1941          * forward to avoid infinite loops, but we still need to copy that
1942          * character. */
1943         last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
1944
1945       match_ok = g_match_info_next (match_info, &tmp_error);
1946     }
1947   g_match_info_free (match_info);
1948   if (tmp_error != NULL)
1949     {
1950       g_propagate_error (error, tmp_error);
1951       g_list_foreach (list, (GFunc)g_free, NULL);
1952       g_list_free (list);
1953       match_info->pos = -1;
1954       return NULL;
1955     }
1956
1957   string_list = g_new (gchar *, g_list_length (list) + 1);
1958   i = 0;
1959   for (last = g_list_last (list); last; last = g_list_previous (last))
1960     string_list[i++] = last->data;
1961   string_list[i] = NULL;
1962   g_list_free (list);
1963
1964   return string_list;
1965 }
1966
1967 enum
1968 {
1969   REPL_TYPE_STRING,
1970   REPL_TYPE_CHARACTER,
1971   REPL_TYPE_SYMBOLIC_REFERENCE,
1972   REPL_TYPE_NUMERIC_REFERENCE,
1973   REPL_TYPE_CHANGE_CASE
1974 }; 
1975
1976 typedef enum
1977 {
1978   CHANGE_CASE_NONE         = 1 << 0,
1979   CHANGE_CASE_UPPER        = 1 << 1,
1980   CHANGE_CASE_LOWER        = 1 << 2,
1981   CHANGE_CASE_UPPER_SINGLE = 1 << 3,
1982   CHANGE_CASE_LOWER_SINGLE = 1 << 4,
1983   CHANGE_CASE_SINGLE_MASK  = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
1984   CHANGE_CASE_LOWER_MASK   = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
1985   CHANGE_CASE_UPPER_MASK   = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
1986 } ChangeCase;
1987
1988 struct _InterpolationData
1989 {
1990   gchar     *text;   
1991   gint       type;   
1992   gint       num;
1993   gchar      c;
1994   ChangeCase change_case;
1995 };
1996
1997 static void
1998 free_interpolation_data (InterpolationData *data)
1999 {
2000   g_free (data->text);
2001   g_free (data);
2002 }
2003
2004 static const gchar *
2005 expand_escape (const gchar        *replacement,
2006                const gchar        *p, 
2007                InterpolationData  *data,
2008                GError            **error)
2009 {
2010   const gchar *q, *r;
2011   gint x, d, h, i;
2012   const gchar *error_detail;
2013   gint base = 0;
2014   GError *tmp_error = NULL;
2015
2016   p++;
2017   switch (*p)
2018     {
2019     case 't':
2020       p++;
2021       data->c = '\t';
2022       data->type = REPL_TYPE_CHARACTER;
2023       break;
2024     case 'n':
2025       p++;
2026       data->c = '\n';
2027       data->type = REPL_TYPE_CHARACTER;
2028       break;
2029     case 'v':
2030       p++;
2031       data->c = '\v';
2032       data->type = REPL_TYPE_CHARACTER;
2033       break;
2034     case 'r':
2035       p++;
2036       data->c = '\r';
2037       data->type = REPL_TYPE_CHARACTER;
2038       break;
2039     case 'f':
2040       p++;
2041       data->c = '\f';
2042       data->type = REPL_TYPE_CHARACTER;
2043       break;
2044     case 'a':
2045       p++;
2046       data->c = '\a';
2047       data->type = REPL_TYPE_CHARACTER;
2048       break;
2049     case 'b':
2050       p++;
2051       data->c = '\b';
2052       data->type = REPL_TYPE_CHARACTER;
2053       break;
2054     case '\\':
2055       p++;
2056       data->c = '\\';
2057       data->type = REPL_TYPE_CHARACTER;
2058       break;
2059     case 'x':
2060       p++;
2061       x = 0;
2062       if (*p == '{')
2063         {
2064           p++;
2065           do 
2066             {
2067               h = g_ascii_xdigit_value (*p);
2068               if (h < 0)
2069                 {
2070                   error_detail = _("hexadecimal digit or '}' expected");
2071                   goto error;
2072                 }
2073               x = x * 16 + h;
2074               p++;
2075             }
2076           while (*p != '}');
2077           p++;
2078         }
2079       else
2080         {
2081           for (i = 0; i < 2; i++)
2082             {
2083               h = g_ascii_xdigit_value (*p);
2084               if (h < 0)
2085                 {
2086                   error_detail = _("hexadecimal digit expected");
2087                   goto error;
2088                 }
2089               x = x * 16 + h;
2090               p++;
2091             }
2092         }
2093       data->type = REPL_TYPE_STRING;
2094       data->text = g_new0 (gchar, 8);
2095       g_unichar_to_utf8 (x, data->text);
2096       break;
2097     case 'l':
2098       p++;
2099       data->type = REPL_TYPE_CHANGE_CASE;
2100       data->change_case = CHANGE_CASE_LOWER_SINGLE;
2101       break;
2102     case 'u':
2103       p++;
2104       data->type = REPL_TYPE_CHANGE_CASE;
2105       data->change_case = CHANGE_CASE_UPPER_SINGLE;
2106       break;
2107     case 'L':
2108       p++;
2109       data->type = REPL_TYPE_CHANGE_CASE;
2110       data->change_case = CHANGE_CASE_LOWER;
2111       break;
2112     case 'U':
2113       p++;
2114       data->type = REPL_TYPE_CHANGE_CASE;
2115       data->change_case = CHANGE_CASE_UPPER;
2116       break;
2117     case 'E':
2118       p++;
2119       data->type = REPL_TYPE_CHANGE_CASE;
2120       data->change_case = CHANGE_CASE_NONE;
2121       break;
2122     case 'g':
2123       p++;
2124       if (*p != '<')
2125         {
2126           error_detail = _("missing '<' in symbolic reference");
2127           goto error;
2128         }
2129       q = p + 1;
2130       do 
2131         {
2132           p++;
2133           if (!*p)
2134             {
2135               error_detail = _("unfinished symbolic reference");
2136               goto error;
2137             }
2138         }
2139       while (*p != '>');
2140       if (p - q == 0)
2141         {
2142           error_detail = _("zero-length symbolic reference");
2143           goto error;
2144         }
2145       if (g_ascii_isdigit (*q))
2146         {
2147           x = 0;
2148           do 
2149             {
2150               h = g_ascii_digit_value (*q);
2151               if (h < 0)
2152                 {
2153                   error_detail = _("digit expected");
2154                   p = q;
2155                   goto error;
2156                 }
2157               x = x * 10 + h;
2158               q++;
2159             }
2160           while (q != p);
2161           data->num = x;
2162           data->type = REPL_TYPE_NUMERIC_REFERENCE;
2163         }
2164       else
2165         {
2166           r = q;
2167           do 
2168             {
2169               if (!g_ascii_isalnum (*r))
2170                 {
2171                   error_detail = _("illegal symbolic reference");
2172                   p = r;
2173                   goto error;
2174                 }
2175               r++;
2176             }
2177           while (r != p);
2178           data->text = g_strndup (q, p - q);
2179           data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
2180         }
2181       p++;
2182       break;
2183     case '0':
2184       /* if \0 is followed by a number is an octal number representing a
2185        * character, else it is a numeric reference. */
2186       if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
2187         {
2188           base = 8;
2189           p = g_utf8_next_char (p);
2190         }
2191     case '1':
2192     case '2':
2193     case '3':
2194     case '4':
2195     case '5':
2196     case '6':
2197     case '7':
2198     case '8':
2199     case '9':
2200       x = 0;
2201       d = 0;
2202       for (i = 0; i < 3; i++)
2203         {
2204           h = g_ascii_digit_value (*p);
2205           if (h < 0) 
2206             break;
2207           if (h > 7)
2208             {
2209               if (base == 8)
2210                 break;
2211               else 
2212                 base = 10;
2213             }
2214           if (i == 2 && base == 10)
2215             break;
2216           x = x * 8 + h;
2217           d = d * 10 + h;
2218           p++;
2219         }
2220       if (base == 8 || i == 3)
2221         {
2222           data->type = REPL_TYPE_STRING;
2223           data->text = g_new0 (gchar, 8);
2224           g_unichar_to_utf8 (x, data->text);
2225         }
2226       else
2227         {
2228           data->type = REPL_TYPE_NUMERIC_REFERENCE;
2229           data->num = d;
2230         }
2231       break;
2232     case 0:
2233       error_detail = _("stray final '\\'");
2234       goto error;
2235       break;
2236     default:
2237       error_detail = _("unknown escape sequence");
2238       goto error;
2239     }
2240
2241   return p;
2242
2243  error:
2244   /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2245   tmp_error = g_error_new (G_REGEX_ERROR, 
2246                            G_REGEX_ERROR_REPLACE,
2247                            _("Error while parsing replacement "
2248                              "text \"%s\" at char %lu: %s"),
2249                            replacement, 
2250                            (gulong)(p - replacement),
2251                            error_detail);
2252   g_propagate_error (error, tmp_error);
2253
2254   return NULL;
2255 }
2256
2257 static GList *
2258 split_replacement (const gchar  *replacement,
2259                    GError      **error)
2260 {
2261   GList *list = NULL;
2262   InterpolationData *data;
2263   const gchar *p, *start;
2264   
2265   start = p = replacement; 
2266   while (*p)
2267     {
2268       if (*p == '\\')
2269         {
2270           data = g_new0 (InterpolationData, 1);
2271           start = p = expand_escape (replacement, p, data, error);
2272           if (p == NULL)
2273             {
2274               g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2275               g_list_free (list);
2276               free_interpolation_data (data);
2277
2278               return NULL;
2279             }
2280           list = g_list_prepend (list, data);
2281         }
2282       else
2283         {
2284           p++;
2285           if (*p == '\\' || *p == '\0')
2286             {
2287               if (p - start > 0)
2288                 {
2289                   data = g_new0 (InterpolationData, 1);
2290                   data->text = g_strndup (start, p - start);
2291                   data->type = REPL_TYPE_STRING;
2292                   list = g_list_prepend (list, data);
2293                 }
2294             }
2295         }
2296     }
2297
2298   return g_list_reverse (list);
2299 }
2300
2301 /* Change the case of c based on change_case. */
2302 #define CHANGE_CASE(c, change_case) \
2303         (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2304                 g_unichar_tolower (c) : \
2305                 g_unichar_toupper (c))
2306
2307 static void
2308 string_append (GString     *string,
2309                const gchar *text,
2310                ChangeCase  *change_case)
2311 {
2312   gunichar c;
2313
2314   if (text[0] == '\0')
2315     return;
2316
2317   if (*change_case == CHANGE_CASE_NONE)
2318     {
2319       g_string_append (string, text);
2320     }
2321   else if (*change_case & CHANGE_CASE_SINGLE_MASK)
2322     {
2323       c = g_utf8_get_char (text);
2324       g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2325       g_string_append (string, g_utf8_next_char (text));
2326       *change_case = CHANGE_CASE_NONE;
2327     }
2328   else
2329     {
2330       while (*text != '\0')
2331         {
2332           c = g_utf8_get_char (text);
2333           g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
2334           text = g_utf8_next_char (text);
2335         }
2336     }
2337 }
2338
2339 static gboolean
2340 interpolate_replacement (const GMatchInfo *match_info,
2341                          GString          *result,
2342                          gpointer          data)
2343 {
2344   GList *list;
2345   InterpolationData *idata;
2346   gchar *match;
2347   ChangeCase change_case = CHANGE_CASE_NONE;
2348
2349   for (list = data; list; list = list->next)
2350     {
2351       idata = list->data;
2352       switch (idata->type)
2353         {
2354         case REPL_TYPE_STRING:
2355           string_append (result, idata->text, &change_case);
2356           break;
2357         case REPL_TYPE_CHARACTER:
2358           g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
2359           if (change_case & CHANGE_CASE_SINGLE_MASK)
2360             change_case = CHANGE_CASE_NONE;
2361           break;
2362         case REPL_TYPE_NUMERIC_REFERENCE:
2363           match = g_match_info_fetch (match_info, idata->num);
2364           if (match)
2365             {
2366               string_append (result, match, &change_case);
2367               g_free (match);
2368             }
2369           break;
2370         case REPL_TYPE_SYMBOLIC_REFERENCE:
2371           match = g_match_info_fetch_named (match_info, idata->text);
2372           if (match)
2373             {
2374               string_append (result, match, &change_case);
2375               g_free (match);
2376             }
2377           break;
2378         case REPL_TYPE_CHANGE_CASE:
2379           change_case = idata->change_case;
2380           break;
2381         }
2382     }
2383
2384   return FALSE; 
2385 }
2386
2387 /* whether actual match_info is needed for replacement, i.e.
2388  * whether there are references
2389  */
2390 static gboolean
2391 interpolation_list_needs_match (GList *list)
2392 {
2393   while (list != NULL)
2394     {
2395       InterpolationData *data = list->data;
2396
2397       if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
2398           data->type == REPL_TYPE_NUMERIC_REFERENCE)
2399         {
2400           return TRUE;
2401         }
2402
2403       list = list->next;
2404     }
2405
2406   return FALSE;
2407 }
2408
2409 /**
2410  * g_regex_replace:
2411  * @regex: a #GRegex structure
2412  * @string: (array length=string_len): the string to perform matches against
2413  * @string_len: the length of @string, or -1 if @string is nul-terminated
2414  * @start_position: starting index of the string to match
2415  * @replacement: text to replace each match with
2416  * @match_options: options for the match
2417  * @error: location to store the error occuring, or %NULL to ignore errors
2418  *
2419  * Replaces all occurrences of the pattern in @regex with the
2420  * replacement text. Backreferences of the form '\number' or 
2421  * '\g&lt;number&gt;' in the replacement text are interpolated by the 
2422  * number-th captured subexpression of the match, '\g&lt;name&gt;' refers 
2423  * to the captured subexpression with the given name. '\0' refers to the 
2424  * complete match, but '\0' followed by a number is the octal representation 
2425  * of a character. To include a literal '\' in the replacement, write '\\'.
2426  * There are also escapes that changes the case of the following text:
2427  *
2428  * <variablelist>
2429  * <varlistentry><term>\l</term>
2430  * <listitem>
2431  * <para>Convert to lower case the next character</para>
2432  * </listitem>
2433  * </varlistentry>
2434  * <varlistentry><term>\u</term>
2435  * <listitem>
2436  * <para>Convert to upper case the next character</para>
2437  * </listitem>
2438  * </varlistentry>
2439  * <varlistentry><term>\L</term>
2440  * <listitem>
2441  * <para>Convert to lower case till \E</para>
2442  * </listitem>
2443  * </varlistentry>
2444  * <varlistentry><term>\U</term>
2445  * <listitem>
2446  * <para>Convert to upper case till \E</para>
2447  * </listitem>
2448  * </varlistentry>
2449  * <varlistentry><term>\E</term>
2450  * <listitem>
2451  * <para>End case modification</para>
2452  * </listitem>
2453  * </varlistentry>
2454  * </variablelist>
2455  *
2456  * If you do not need to use backreferences use g_regex_replace_literal().
2457  *
2458  * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2459  * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2460  * you can use g_regex_replace_literal().
2461  *
2462  * Setting @start_position differs from just passing over a shortened 
2463  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that 
2464  * begins with any kind of lookbehind assertion, such as "\b".
2465  *
2466  * Returns: a newly allocated string containing the replacements
2467  *
2468  * Since: 2.14
2469  */
2470 gchar *
2471 g_regex_replace (const GRegex      *regex, 
2472                  const gchar       *string, 
2473                  gssize             string_len,
2474                  gint               start_position,
2475                  const gchar       *replacement,
2476                  GRegexMatchFlags   match_options,
2477                  GError           **error)
2478 {
2479   gchar *result;
2480   GList *list;
2481   GError *tmp_error = NULL;
2482
2483   g_return_val_if_fail (regex != NULL, NULL);
2484   g_return_val_if_fail (string != NULL, NULL);
2485   g_return_val_if_fail (start_position >= 0, NULL);
2486   g_return_val_if_fail (replacement != NULL, NULL);
2487   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2488   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2489
2490   list = split_replacement (replacement, &tmp_error);
2491   if (tmp_error != NULL)
2492     {
2493       g_propagate_error (error, tmp_error);
2494       return NULL;
2495     }
2496
2497   result = g_regex_replace_eval (regex, 
2498                                  string, string_len, start_position,
2499                                  match_options,
2500                                  interpolate_replacement,
2501                                  (gpointer)list,
2502                                  &tmp_error);
2503   if (tmp_error != NULL)
2504     g_propagate_error (error, tmp_error);
2505
2506   g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
2507   g_list_free (list);
2508
2509   return result;
2510 }
2511
2512 static gboolean
2513 literal_replacement (const GMatchInfo *match_info,
2514                      GString          *result,
2515                      gpointer          data)
2516 {
2517   g_string_append (result, data);
2518   return FALSE;
2519 }
2520
2521 /**
2522  * g_regex_replace_literal:
2523  * @regex: a #GRegex structure
2524  * @string: (array length=string_len): the string to perform matches against
2525  * @string_len: the length of @string, or -1 if @string is nul-terminated
2526  * @start_position: starting index of the string to match
2527  * @replacement: text to replace each match with
2528  * @match_options: options for the match
2529  * @error: location to store the error occuring, or %NULL to ignore errors
2530  *
2531  * Replaces all occurrences of the pattern in @regex with the
2532  * replacement text. @replacement is replaced literally, to
2533  * include backreferences use g_regex_replace().
2534  *
2535  * Setting @start_position differs from just passing over a 
2536  * shortened string and setting #G_REGEX_MATCH_NOTBOL in the 
2537  * case of a pattern that begins with any kind of lookbehind 
2538  * assertion, such as "\b".
2539  *
2540  * Returns: a newly allocated string containing the replacements
2541  *
2542  * Since: 2.14
2543  */
2544 gchar *
2545 g_regex_replace_literal (const GRegex      *regex,
2546                          const gchar       *string,
2547                          gssize             string_len,
2548                          gint               start_position,
2549                          const gchar       *replacement,
2550                          GRegexMatchFlags   match_options,
2551                          GError           **error)
2552 {
2553   g_return_val_if_fail (replacement != NULL, NULL);
2554   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2555
2556   return g_regex_replace_eval (regex,
2557                                string, string_len, start_position,
2558                                match_options,
2559                                literal_replacement,
2560                                (gpointer)replacement,
2561                                error);
2562 }
2563
2564 /**
2565  * g_regex_replace_eval:
2566  * @regex: a #GRegex structure from g_regex_new()
2567  * @string (array length=string_len): string to perform matches against
2568  * @string_len: the length of @string, or -1 if @string is nul-terminated
2569  * @start_position: starting index of the string to match
2570  * @match_options: options for the match
2571  * @eval: a function to call for each match
2572  * @user_data: user data to pass to the function
2573  * @error: location to store the error occuring, or %NULL to ignore errors
2574  *
2575  * Replaces occurrences of the pattern in regex with the output of 
2576  * @eval for that occurrence.
2577  *
2578  * Setting @start_position differs from just passing over a shortened 
2579  * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern 
2580  * that begins with any kind of lookbehind assertion, such as "\b".
2581  *
2582  * The following example uses g_regex_replace_eval() to replace multiple
2583  * strings at once:
2584  * |[
2585  * static gboolean 
2586  * eval_cb (const GMatchInfo *info,          
2587  *          GString          *res,
2588  *          gpointer          data)
2589  * {
2590  *   gchar *match;
2591  *   gchar *r;
2592  * 
2593  *    match = g_match_info_fetch (info, 0);
2594  *    r = g_hash_table_lookup ((GHashTable *)data, match);
2595  *    g_string_append (res, r);
2596  *    g_free (match);
2597  * 
2598  *    return FALSE;
2599  * }
2600  * 
2601  * /&ast; ... &ast;/
2602  * 
2603  * GRegex *reg;
2604  * GHashTable *h;
2605  * gchar *res;
2606  *
2607  * h = g_hash_table_new (g_str_hash, g_str_equal);
2608  * 
2609  * g_hash_table_insert (h, "1", "ONE");
2610  * g_hash_table_insert (h, "2", "TWO");
2611  * g_hash_table_insert (h, "3", "THREE");
2612  * g_hash_table_insert (h, "4", "FOUR");
2613  * 
2614  * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2615  * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2616  * g_hash_table_destroy (h);
2617  *
2618  * /&ast; ... &ast;/
2619  * ]|
2620  *
2621  * Returns: a newly allocated string containing the replacements
2622  *
2623  * Since: 2.14
2624  */
2625 gchar *
2626 g_regex_replace_eval (const GRegex        *regex,
2627                       const gchar         *string,
2628                       gssize               string_len,
2629                       gint                 start_position,
2630                       GRegexMatchFlags     match_options,
2631                       GRegexEvalCallback   eval,
2632                       gpointer             user_data,
2633                       GError             **error)
2634 {
2635   GMatchInfo *match_info;
2636   GString *result;
2637   gint str_pos = 0;
2638   gboolean done = FALSE;
2639   GError *tmp_error = NULL;
2640
2641   g_return_val_if_fail (regex != NULL, NULL);
2642   g_return_val_if_fail (string != NULL, NULL);
2643   g_return_val_if_fail (start_position >= 0, NULL);
2644   g_return_val_if_fail (eval != NULL, NULL);
2645   g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
2646
2647   if (string_len < 0)
2648     string_len = strlen (string);
2649
2650   result = g_string_sized_new (string_len);
2651
2652   /* run down the string making matches. */
2653   g_regex_match_full (regex, string, string_len, start_position,
2654                       match_options, &match_info, &tmp_error);
2655   while (!done && g_match_info_matches (match_info))
2656     {
2657       g_string_append_len (result,
2658                            string + str_pos,
2659                            match_info->offsets[0] - str_pos);
2660       done = (*eval) (match_info, result, user_data);
2661       str_pos = match_info->offsets[1];
2662       g_match_info_next (match_info, &tmp_error);
2663     }
2664   g_match_info_free (match_info);
2665   if (tmp_error != NULL)
2666     {
2667       g_propagate_error (error, tmp_error);
2668       g_string_free (result, TRUE);
2669       return NULL;
2670     }
2671
2672   g_string_append_len (result, string + str_pos, string_len - str_pos);
2673   return g_string_free (result, FALSE);
2674 }
2675
2676 /**
2677  * g_regex_check_replacement:
2678  * @replacement: the replacement string
2679  * @has_references: (out) (allow-none): location to store information about
2680  *   references in @replacement or %NULL
2681  * @error: location to store error
2682  *
2683  * Checks whether @replacement is a valid replacement string 
2684  * (see g_regex_replace()), i.e. that all escape sequences in 
2685  * it are valid.
2686  *
2687  * If @has_references is not %NULL then @replacement is checked 
2688  * for pattern references. For instance, replacement text 'foo\n'
2689  * does not contain references and may be evaluated without information
2690  * about actual match, but '\0\1' (whole match followed by first 
2691  * subpattern) requires valid #GMatchInfo object.
2692  *
2693  * Returns: whether @replacement is a valid replacement string
2694  *
2695  * Since: 2.14
2696  */
2697 gboolean
2698 g_regex_check_replacement (const gchar  *replacement,
2699                            gboolean     *has_references,
2700                            GError      **error)
2701 {
2702   GList *list;
2703   GError *tmp = NULL;
2704
2705   list = split_replacement (replacement, &tmp);
2706
2707   if (tmp)
2708   {
2709     g_propagate_error (error, tmp);
2710     return FALSE;
2711   }
2712
2713   if (has_references)
2714     *has_references = interpolation_list_needs_match (list);
2715
2716   g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
2717   g_list_free (list);
2718
2719   return TRUE;
2720 }
2721
2722 /**
2723  * g_regex_escape_string:
2724  * @string: (array length=length): the string to escape
2725  * @length: the length of @string, or -1 if @string is nul-terminated
2726  *
2727  * Escapes the special characters used for regular expressions 
2728  * in @string, for instance "a.b*c" becomes "a\.b\*c". This 
2729  * function is useful to dynamically generate regular expressions.
2730  *
2731  * @string can contain nul characters that are replaced with "\0", 
2732  * in this case remember to specify the correct length of @string 
2733  * in @length.
2734  *
2735  * Returns: a newly-allocated escaped string
2736  *
2737  * Since: 2.14
2738  */
2739 gchar *
2740 g_regex_escape_string (const gchar *string,
2741                        gint         length)
2742 {
2743   GString *escaped;
2744   const char *p, *piece_start, *end;
2745
2746   g_return_val_if_fail (string != NULL, NULL);
2747
2748   if (length < 0)
2749     length = strlen (string);
2750
2751   end = string + length;
2752   p = piece_start = string;
2753   escaped = g_string_sized_new (length + 1);
2754
2755   while (p < end)
2756     {
2757       switch (*p)
2758         {
2759         case '\0':
2760         case '\\':
2761         case '|':
2762         case '(':
2763         case ')':
2764         case '[':
2765         case ']':
2766         case '{':
2767         case '}':
2768         case '^':
2769         case '$':
2770         case '*':
2771         case '+':
2772         case '?':
2773         case '.':
2774           if (p != piece_start)
2775             /* copy the previous piece. */
2776             g_string_append_len (escaped, piece_start, p - piece_start);
2777           g_string_append_c (escaped, '\\');
2778           if (*p == '\0')
2779             g_string_append_c (escaped, '0');
2780           else
2781             g_string_append_c (escaped, *p);
2782           piece_start = ++p;
2783           break;
2784         default:
2785           p = g_utf8_next_char (p);
2786           break;
2787         } 
2788   }
2789
2790   if (piece_start < end)
2791     g_string_append_len (escaped, piece_start, end - piece_start);
2792
2793   return g_string_free (escaped, FALSE);
2794 }