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