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