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