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