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