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