1 /* GRegex -- regular expression API wrapper around PCRE.
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>
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.
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.
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
26 #ifdef USE_SYSTEM_PCRE
29 #include "pcre/pcre.h"
36 #include "gmessages.h"
37 #include "gstrfuncs.h"
43 * @title: Perl-compatible regular expressions
44 * @short_description: matches strings against regular expressions
45 * @see_also: <xref linkend="glib-regex-syntax"/>
47 * The <function>g_regex_*()</function> functions implement regular
48 * expression pattern matching using syntax and semantics similar to
49 * Perl regular expression.
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.
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. "à") 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.
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).
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.
91 * When setting the %G_REGEX_JAVASCRIPT_COMPAT flag, pattern syntax and pattern
92 * matching is changed to be compatible with the way that regular expressions
93 * work in JavaScript. More precisely, a lonely ']' character in the pattern
94 * is a syntax error; the '\x' escape only allows 0 to 2 hexadecimal digits, and
95 * you must use the '\u' escape sequence with 4 hex digits to specify a unicode
96 * codepoint instead of '\x' or 'x{....}'. If '\x' or '\u' are not followed by
97 * the specified number of hex digits, they match 'x' and 'u' literally; also
98 * '\U' always matches 'U' instead of being an error in the pattern. Finally,
99 * pattern matching is modified so that back references to an unset subpattern
100 * group produces a match with the empty string instead of an error. See
101 * <ulink>man:pcreapi(3)</ulink> for more information.
103 * Creating and manipulating the same #GRegex structure from different
104 * threads is not a problem as #GRegex does not modify its internal
105 * state between creation and destruction, on the other hand #GMatchInfo
108 * The regular expressions low-level functionalities are obtained through
109 * the excellent <ulink url="http://www.pcre.org/">PCRE</ulink> library
110 * written by Philip Hazel.
113 /* Mask of all the possible values for GRegexCompileFlags. */
114 #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
115 G_REGEX_MULTILINE | \
119 G_REGEX_DOLLAR_ENDONLY | \
122 G_REGEX_NO_AUTO_CAPTURE | \
124 G_REGEX_FIRSTLINE | \
126 G_REGEX_NEWLINE_CR | \
127 G_REGEX_NEWLINE_LF | \
128 G_REGEX_NEWLINE_CRLF | \
129 G_REGEX_NEWLINE_ANYCRLF | \
130 G_REGEX_BSR_ANYCRLF | \
131 G_REGEX_JAVASCRIPT_COMPAT)
133 /* Mask of all GRegexCompileFlags values that are (not) passed trough to PCRE */
134 #define G_REGEX_COMPILE_PCRE_MASK (G_REGEX_COMPILE_MASK & ~G_REGEX_COMPILE_NONPCRE_MASK)
135 #define G_REGEX_COMPILE_NONPCRE_MASK (G_REGEX_RAW | \
138 /* Mask of all the possible values for GRegexMatchFlags. */
139 #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
140 G_REGEX_MATCH_NOTBOL | \
141 G_REGEX_MATCH_NOTEOL | \
142 G_REGEX_MATCH_NOTEMPTY | \
143 G_REGEX_MATCH_PARTIAL | \
144 G_REGEX_MATCH_NEWLINE_CR | \
145 G_REGEX_MATCH_NEWLINE_LF | \
146 G_REGEX_MATCH_NEWLINE_CRLF | \
147 G_REGEX_MATCH_NEWLINE_ANY | \
148 G_REGEX_MATCH_NEWLINE_ANYCRLF | \
149 G_REGEX_MATCH_BSR_ANYCRLF | \
150 G_REGEX_MATCH_BSR_ANY | \
151 G_REGEX_MATCH_PARTIAL_SOFT | \
152 G_REGEX_MATCH_PARTIAL_HARD | \
153 G_REGEX_MATCH_NOTEMPTY_ATSTART)
155 /* we rely on these flags having the same values */
156 G_STATIC_ASSERT (G_REGEX_CASELESS
== PCRE_CASELESS
);
157 G_STATIC_ASSERT (G_REGEX_MULTILINE
== PCRE_MULTILINE
);
158 G_STATIC_ASSERT (G_REGEX_DOTALL
== PCRE_DOTALL
);
159 G_STATIC_ASSERT (G_REGEX_EXTENDED
== PCRE_EXTENDED
);
160 G_STATIC_ASSERT (G_REGEX_ANCHORED
== PCRE_ANCHORED
);
161 G_STATIC_ASSERT (G_REGEX_DOLLAR_ENDONLY
== PCRE_DOLLAR_ENDONLY
);
162 G_STATIC_ASSERT (G_REGEX_UNGREEDY
== PCRE_UNGREEDY
);
163 G_STATIC_ASSERT (G_REGEX_NO_AUTO_CAPTURE
== PCRE_NO_AUTO_CAPTURE
);
164 G_STATIC_ASSERT (G_REGEX_FIRSTLINE
== PCRE_FIRSTLINE
);
165 G_STATIC_ASSERT (G_REGEX_DUPNAMES
== PCRE_DUPNAMES
);
166 G_STATIC_ASSERT (G_REGEX_NEWLINE_CR
== PCRE_NEWLINE_CR
);
167 G_STATIC_ASSERT (G_REGEX_NEWLINE_LF
== PCRE_NEWLINE_LF
);
168 G_STATIC_ASSERT (G_REGEX_NEWLINE_CRLF
== PCRE_NEWLINE_CRLF
);
169 G_STATIC_ASSERT (G_REGEX_NEWLINE_ANYCRLF
== PCRE_NEWLINE_ANYCRLF
);
170 G_STATIC_ASSERT (G_REGEX_BSR_ANYCRLF
== PCRE_BSR_ANYCRLF
);
171 G_STATIC_ASSERT (G_REGEX_JAVASCRIPT_COMPAT
== PCRE_JAVASCRIPT_COMPAT
);
173 G_STATIC_ASSERT (G_REGEX_MATCH_ANCHORED
== PCRE_ANCHORED
);
174 G_STATIC_ASSERT (G_REGEX_MATCH_NOTBOL
== PCRE_NOTBOL
);
175 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEOL
== PCRE_NOTEOL
);
176 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY
== PCRE_NOTEMPTY
);
177 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL
== PCRE_PARTIAL
);
178 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CR
== PCRE_NEWLINE_CR
);
179 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_LF
== PCRE_NEWLINE_LF
);
180 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_CRLF
== PCRE_NEWLINE_CRLF
);
181 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANY
== PCRE_NEWLINE_ANY
);
182 G_STATIC_ASSERT (G_REGEX_MATCH_NEWLINE_ANYCRLF
== PCRE_NEWLINE_ANYCRLF
);
183 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANYCRLF
== PCRE_BSR_ANYCRLF
);
184 G_STATIC_ASSERT (G_REGEX_MATCH_BSR_ANY
== PCRE_BSR_UNICODE
);
185 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL_SOFT
== PCRE_PARTIAL_SOFT
);
186 G_STATIC_ASSERT (G_REGEX_MATCH_PARTIAL_HARD
== PCRE_PARTIAL_HARD
);
187 G_STATIC_ASSERT (G_REGEX_MATCH_NOTEMPTY_ATSTART
== PCRE_NOTEMPTY_ATSTART
);
189 /* These PCRE flags are unused or not exposed publically in GRegexFlags, so
190 * it should be ok to reuse them for different things.
192 G_STATIC_ASSERT (G_REGEX_OPTIMIZE
== PCRE_NO_UTF8_CHECK
);
193 G_STATIC_ASSERT (G_REGEX_RAW
== PCRE_UTF8
);
195 /* if the string is in UTF-8 use g_utf8_ functions, else use
197 #define NEXT_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
199 g_utf8_next_char (s))
200 #define PREV_CHAR(re, s) (((re)->compile_opts & G_REGEX_RAW) ? \
202 g_utf8_prev_char (s))
206 volatile gint ref_count
; /* the ref count */
207 GRegex
*regex
; /* the regex */
208 GRegexMatchFlags match_opts
; /* options used at match time on the regex */
209 gint matches
; /* number of matching sub patterns */
210 gint pos
; /* position in the string where last match left off */
211 gint n_offsets
; /* number of offsets */
212 gint
*offsets
; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
213 gint
*workspace
; /* workspace for pcre_dfa_exec() */
214 gint n_workspace
; /* number of workspace elements */
215 const gchar
*string
; /* string passed to the match function */
216 gssize string_len
; /* length of string */
221 volatile gint ref_count
; /* the ref count for the immutable part */
222 gchar
*pattern
; /* the pattern */
223 pcre
*pcre_re
; /* compiled form of the pattern */
224 GRegexCompileFlags compile_opts
; /* options used at compile time on the pattern */
225 GRegexMatchFlags match_opts
; /* options used at match time on the regex */
226 pcre_extra
*extra
; /* data stored when G_REGEX_OPTIMIZE is used */
229 /* TRUE if ret is an error code, FALSE otherwise. */
230 #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
232 typedef struct _InterpolationData InterpolationData
;
233 static gboolean
interpolation_list_needs_match (GList
*list
);
234 static gboolean
interpolate_replacement (const GMatchInfo
*match_info
,
237 static GList
*split_replacement (const gchar
*replacement
,
239 static void free_interpolation_data (InterpolationData
*data
);
243 match_error (gint errcode
)
247 case PCRE_ERROR_NOMATCH
:
250 case PCRE_ERROR_NULL
:
251 /* NULL argument, this should not happen in GRegex */
252 g_warning ("A NULL argument was passed to PCRE");
254 case PCRE_ERROR_BADOPTION
:
255 return "bad options";
256 case PCRE_ERROR_BADMAGIC
:
257 return _("corrupted object");
258 case PCRE_ERROR_UNKNOWN_OPCODE
:
259 return N_("internal error or corrupted object");
260 case PCRE_ERROR_NOMEMORY
:
261 return _("out of memory");
262 case PCRE_ERROR_NOSUBSTRING
:
263 /* not used by pcre_exec() */
265 case PCRE_ERROR_MATCHLIMIT
:
266 return _("backtracking limit reached");
267 case PCRE_ERROR_CALLOUT
:
268 /* callouts are not implemented */
270 case PCRE_ERROR_BADUTF8
:
271 case PCRE_ERROR_BADUTF8_OFFSET
:
272 /* we do not check if strings are valid */
274 case PCRE_ERROR_PARTIAL
:
277 case PCRE_ERROR_BADPARTIAL
:
278 return _("the pattern contains items not supported for partial matching");
279 case PCRE_ERROR_INTERNAL
:
280 return _("internal error");
281 case PCRE_ERROR_BADCOUNT
:
282 /* negative ovecsize, this should not happen in GRegex */
283 g_warning ("A negative ovecsize was passed to PCRE");
285 case PCRE_ERROR_DFA_UITEM
:
286 return _("the pattern contains items not supported for partial matching");
287 case PCRE_ERROR_DFA_UCOND
:
288 return _("back references as conditions are not supported for partial matching");
289 case PCRE_ERROR_DFA_UMLIMIT
:
290 /* the match_field field is not used in GRegex */
292 case PCRE_ERROR_DFA_WSSIZE
:
293 /* handled expanding the workspace */
295 case PCRE_ERROR_DFA_RECURSE
:
296 case PCRE_ERROR_RECURSIONLIMIT
:
297 return _("recursion limit reached");
298 case PCRE_ERROR_BADNEWLINE
:
299 return _("invalid combination of newline flags");
300 case PCRE_ERROR_BADOFFSET
:
301 return _("bad offset");
302 case PCRE_ERROR_SHORTUTF8
:
303 return _("short utf8");
304 case PCRE_ERROR_RECURSELOOP
:
305 return _("recursion loop");
309 return _("unknown error");
313 translate_compile_error (gint
*errcode
, const gchar
**errmsg
)
315 /* Compile errors are created adding 100 to the error code returned
317 * If errcode is known we put the translatable error message in
318 * erromsg. If errcode is unknown we put the generic
319 * G_REGEX_ERROR_COMPILE error code in errcode and keep the
320 * untranslated error message returned by PCRE.
321 * Note that there can be more PCRE errors with the same GRegexError
322 * and that some PCRE errors are useless for us.
328 case G_REGEX_ERROR_STRAY_BACKSLASH
:
329 *errmsg
= _("\\ at end of pattern");
331 case G_REGEX_ERROR_MISSING_CONTROL_CHAR
:
332 *errmsg
= _("\\c at end of pattern");
334 case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE
:
335 *errmsg
= _("unrecognized character following \\");
337 case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER
:
338 *errmsg
= _("numbers out of order in {} quantifier");
340 case G_REGEX_ERROR_QUANTIFIER_TOO_BIG
:
341 *errmsg
= _("number too big in {} quantifier");
343 case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS
:
344 *errmsg
= _("missing terminating ] for character class");
346 case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS
:
347 *errmsg
= _("invalid escape sequence in character class");
349 case G_REGEX_ERROR_RANGE_OUT_OF_ORDER
:
350 *errmsg
= _("range out of order in character class");
352 case G_REGEX_ERROR_NOTHING_TO_REPEAT
:
353 *errmsg
= _("nothing to repeat");
355 case 111: /* internal error: unexpected repeat */
356 *errcode
= G_REGEX_ERROR_INTERNAL
;
357 *errmsg
= _("unexpected repeat");
359 case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER
:
360 *errmsg
= _("unrecognized character after (? or (?-");
362 case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS
:
363 *errmsg
= _("POSIX named classes are supported only within a class");
365 case G_REGEX_ERROR_UNMATCHED_PARENTHESIS
:
366 *errmsg
= _("missing terminating )");
368 case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE
:
369 *errmsg
= _("reference to non-existent subpattern");
371 case G_REGEX_ERROR_UNTERMINATED_COMMENT
:
372 *errmsg
= _("missing ) after comment");
374 case G_REGEX_ERROR_EXPRESSION_TOO_LARGE
:
375 *errmsg
= _("regular expression is too large");
377 case G_REGEX_ERROR_MEMORY_ERROR
:
378 *errmsg
= _("failed to get memory");
380 case 122: /* unmatched parentheses */
381 *errcode
= G_REGEX_ERROR_UNMATCHED_PARENTHESIS
;
382 *errmsg
= _(") without opening (");
384 case 123: /* internal error: code overflow */
385 *errcode
= G_REGEX_ERROR_INTERNAL
;
386 *errmsg
= _("code overflow");
388 case 124: /* "unrecognized character after (?<\0 */
389 *errcode
= G_REGEX_ERROR_UNRECOGNIZED_CHARACTER
;
390 *errmsg
= _("unrecognized character after (?<");
392 case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND
:
393 *errmsg
= _("lookbehind assertion is not fixed length");
395 case G_REGEX_ERROR_MALFORMED_CONDITION
:
396 *errmsg
= _("malformed number or name after (?(");
398 case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES
:
399 *errmsg
= _("conditional group contains more than two branches");
401 case G_REGEX_ERROR_ASSERTION_EXPECTED
:
402 *errmsg
= _("assertion expected after (?(");
405 *errcode
= G_REGEX_ERROR_UNMATCHED_PARENTHESIS
;
406 /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
407 * sequences here, '(?-54' would be an example for the second group.
409 *errmsg
= _("(?R or (?[+-]digits must be followed by )");
411 case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME
:
412 *errmsg
= _("unknown POSIX class name");
414 case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED
:
415 *errmsg
= _("POSIX collating elements are not supported");
417 case G_REGEX_ERROR_HEX_CODE_TOO_LARGE
:
418 *errmsg
= _("character value in \\x{...} sequence is too large");
420 case G_REGEX_ERROR_INVALID_CONDITION
:
421 *errmsg
= _("invalid condition (?(0)");
423 case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND
:
424 *errmsg
= _("\\C not allowed in lookbehind assertion");
426 case 137: /* PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0 */
427 /* A number of Perl escapes are not handled by PCRE.
428 * Therefore it explicitly raises ERR37.
430 *errcode
= G_REGEX_ERROR_UNRECOGNIZED_ESCAPE
;
431 *errmsg
= _("escapes \\L, \\l, \\N{name}, \\U, and \\u are not supported");
433 case G_REGEX_ERROR_INFINITE_LOOP
:
434 *errmsg
= _("recursive call could loop indefinitely");
436 case 141: /* unrecognized character after (?P\0 */
437 *errcode
= G_REGEX_ERROR_UNRECOGNIZED_CHARACTER
;
438 *errmsg
= _("unrecognized character after (?P");
440 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR
:
441 *errmsg
= _("missing terminator in subpattern name");
443 case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME
:
444 *errmsg
= _("two named subpatterns have the same name");
446 case G_REGEX_ERROR_MALFORMED_PROPERTY
:
447 *errmsg
= _("malformed \\P or \\p sequence");
449 case G_REGEX_ERROR_UNKNOWN_PROPERTY
:
450 *errmsg
= _("unknown property name after \\P or \\p");
452 case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG
:
453 *errmsg
= _("subpattern name is too long (maximum 32 characters)");
455 case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS
:
456 *errmsg
= _("too many named subpatterns (maximum 10,000)");
458 case G_REGEX_ERROR_INVALID_OCTAL_VALUE
:
459 *errmsg
= _("octal value is greater than \\377");
461 case 152: /* internal error: overran compiling workspace */
462 *errcode
= G_REGEX_ERROR_INTERNAL
;
463 *errmsg
= _("overran compiling workspace");
465 case 153: /* internal error: previously-checked referenced subpattern not found */
466 *errcode
= G_REGEX_ERROR_INTERNAL
;
467 *errmsg
= _("previously-checked referenced subpattern not found");
469 case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE
:
470 *errmsg
= _("DEFINE group contains more than one branch");
472 case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS
:
473 *errmsg
= _("inconsistent NEWLINE options");
475 case G_REGEX_ERROR_MISSING_BACK_REFERENCE
:
476 *errmsg
= _("\\g is not followed by a braced, angle-bracketed, or quoted name or "
477 "number, or by a plain number");
479 case G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE
:
480 *errmsg
= _("a numbered reference must not be zero");
482 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN
:
483 *errmsg
= _("an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)");
485 case G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB
:
486 *errmsg
= _("(*VERB) not recognized");
488 case G_REGEX_ERROR_NUMBER_TOO_BIG
:
489 *errmsg
= _("number is too big");
491 case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME
:
492 *errmsg
= _("missing subpattern name after (?&");
494 case G_REGEX_ERROR_MISSING_DIGIT
:
495 *errmsg
= _("digit expected after (?+");
497 case G_REGEX_ERROR_INVALID_DATA_CHARACTER
:
498 *errmsg
= _("] is an invalid data character in JavaScript compatibility mode");
500 case G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME
:
501 *errmsg
= _("different names for subpatterns of the same number are not allowed");
503 case G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED
:
504 *errmsg
= _("(*MARK) must have an argument");
506 case G_REGEX_ERROR_INVALID_CONTROL_CHAR
:
507 *errmsg
= _( "\\c must be followed by an ASCII character");
509 case G_REGEX_ERROR_MISSING_NAME
:
510 *errmsg
= _("\\k is not followed by a braced, angle-bracketed, or quoted name");
512 case G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS
:
513 *errmsg
= _("\\N is not supported in a class");
515 case G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES
:
516 *errmsg
= _("too many forward references");
518 case G_REGEX_ERROR_NAME_TOO_LONG
:
519 *errmsg
= _("name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)");
521 case G_REGEX_ERROR_CHARACTER_VALUE_TOO_LARGE
:
522 *errmsg
= _("character value in \\u.... sequence is too large");
525 case 116: /* erroffset passed as NULL */
526 /* This should not happen as we never pass a NULL erroffset */
527 g_warning ("erroffset passed as NULL");
528 *errcode
= G_REGEX_ERROR_COMPILE
;
530 case 117: /* unknown option bit(s) set */
531 /* This should not happen as we check options before passing them
532 * to pcre_compile2() */
533 g_warning ("unknown option bit(s) set");
534 *errcode
= G_REGEX_ERROR_COMPILE
;
536 case 132: /* this version of PCRE is compiled without UTF support */
537 case 144: /* invalid UTF-8 string */
538 case 145: /* support for \\P, \\p, and \\X has not been compiled */
539 case 167: /* this version of PCRE is not compiled with Unicode property support */
540 case 173: /* disallowed Unicode code point (>= 0xd800 && <= 0xdfff) */
541 case 174: /* invalid UTF-16 string */
542 /* These errors should not happen as we are using an UTF-8 and UCP-enabled PCRE
543 * and we do not check if strings are valid */
544 case 170: /* internal error: unknown opcode in find_fixedlength() */
545 *errcode
= G_REGEX_ERROR_INTERNAL
;
549 *errcode
= G_REGEX_ERROR_COMPILE
;
556 match_info_new (const GRegex
*regex
,
563 GMatchInfo
*match_info
;
566 string_len
= strlen (string
);
568 match_info
= g_new0 (GMatchInfo
, 1);
569 match_info
->ref_count
= 1;
570 match_info
->regex
= g_regex_ref ((GRegex
*)regex
);
571 match_info
->string
= string
;
572 match_info
->string_len
= string_len
;
573 match_info
->matches
= PCRE_ERROR_NOMATCH
;
574 match_info
->pos
= start_position
;
575 match_info
->match_opts
= match_options
;
579 /* These values should be enough for most cases, if they are not
580 * enough g_regex_match_all_full() will expand them. */
581 match_info
->n_offsets
= 24;
582 match_info
->n_workspace
= 100;
583 match_info
->workspace
= g_new (gint
, match_info
->n_workspace
);
588 pcre_fullinfo (regex
->pcre_re
, regex
->extra
,
589 PCRE_INFO_CAPTURECOUNT
, &capture_count
);
590 match_info
->n_offsets
= (capture_count
+ 1) * 3;
593 match_info
->offsets
= g_new0 (gint
, match_info
->n_offsets
);
594 /* Set an invalid position for the previous match. */
595 match_info
->offsets
[0] = -1;
596 match_info
->offsets
[1] = -1;
602 * g_match_info_get_regex:
603 * @match_info: a #GMatchInfo
605 * Returns #GRegex object used in @match_info. It belongs to Glib
606 * and must not be freed. Use g_regex_ref() if you need to keep it
607 * after you free @match_info object.
609 * Returns: #GRegex object used in @match_info
614 g_match_info_get_regex (const GMatchInfo
*match_info
)
616 g_return_val_if_fail (match_info
!= NULL
, NULL
);
617 return match_info
->regex
;
621 * g_match_info_get_string:
622 * @match_info: a #GMatchInfo
624 * Returns the string searched with @match_info. This is the
625 * string passed to g_regex_match() or g_regex_replace() so
626 * you may not free it before calling this function.
628 * Returns: the string searched with @match_info
633 g_match_info_get_string (const GMatchInfo
*match_info
)
635 g_return_val_if_fail (match_info
!= NULL
, NULL
);
636 return match_info
->string
;
641 * @match_info: a #GMatchInfo
643 * Increases reference count of @match_info by 1.
645 * Returns: @match_info
650 g_match_info_ref (GMatchInfo
*match_info
)
652 g_return_val_if_fail (match_info
!= NULL
, NULL
);
653 g_atomic_int_inc (&match_info
->ref_count
);
658 * g_match_info_unref:
659 * @match_info: a #GMatchInfo
661 * Decreases reference count of @match_info by 1. When reference count drops
662 * to zero, it frees all the memory associated with the match_info structure.
667 g_match_info_unref (GMatchInfo
*match_info
)
669 if (g_atomic_int_dec_and_test (&match_info
->ref_count
))
671 g_regex_unref (match_info
->regex
);
672 g_free (match_info
->offsets
);
673 g_free (match_info
->workspace
);
680 * @match_info: (allow-none): a #GMatchInfo, or %NULL
682 * If @match_info is not %NULL, calls g_match_info_unref(); otherwise does
688 g_match_info_free (GMatchInfo
*match_info
)
690 if (match_info
== NULL
)
693 g_match_info_unref (match_info
);
698 * @match_info: a #GMatchInfo structure
699 * @error: location to store the error occurring, or %NULL to ignore errors
701 * Scans for the next match using the same parameters of the previous
702 * call to g_regex_match_full() or g_regex_match() that returned
705 * The match is done on the string passed to the match function, so you
706 * cannot free it before calling this function.
708 * Returns: %TRUE is the string matched, %FALSE otherwise
713 g_match_info_next (GMatchInfo
*match_info
,
716 gint prev_match_start
;
719 g_return_val_if_fail (match_info
!= NULL
, FALSE
);
720 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
721 g_return_val_if_fail (match_info
->pos
>= 0, FALSE
);
723 prev_match_start
= match_info
->offsets
[0];
724 prev_match_end
= match_info
->offsets
[1];
726 if (match_info
->pos
> match_info
->string_len
)
728 /* we have reached the end of the string */
729 match_info
->pos
= -1;
730 match_info
->matches
= PCRE_ERROR_NOMATCH
;
734 match_info
->matches
= pcre_exec (match_info
->regex
->pcre_re
,
735 match_info
->regex
->extra
,
737 match_info
->string_len
,
739 match_info
->regex
->match_opts
| match_info
->match_opts
,
741 match_info
->n_offsets
);
742 if (IS_PCRE_ERROR (match_info
->matches
))
744 g_set_error (error
, G_REGEX_ERROR
, G_REGEX_ERROR_MATCH
,
745 _("Error while matching regular expression %s: %s"),
746 match_info
->regex
->pattern
, match_error (match_info
->matches
));
750 /* avoid infinite loops if the pattern is an empty string or something
752 if (match_info
->pos
== match_info
->offsets
[1])
754 if (match_info
->pos
> match_info
->string_len
)
756 /* we have reached the end of the string */
757 match_info
->pos
= -1;
758 match_info
->matches
= PCRE_ERROR_NOMATCH
;
762 match_info
->pos
= NEXT_CHAR (match_info
->regex
,
763 &match_info
->string
[match_info
->pos
]) -
768 match_info
->pos
= match_info
->offsets
[1];
771 /* it's possible to get two identical matches when we are matching
772 * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
773 * the string is "RegExTest" we have:
774 * - search at position 0: match from 0 to 0
775 * - search at position 1: match from 3 to 3
776 * - search at position 3: match from 3 to 3 (duplicate)
777 * - search at position 4: match from 5 to 5
778 * - search at position 5: match from 5 to 5 (duplicate)
779 * - search at position 6: no match -> stop
780 * so we have to ignore the duplicates.
781 * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
782 if (match_info
->matches
>= 0 &&
783 prev_match_start
== match_info
->offsets
[0] &&
784 prev_match_end
== match_info
->offsets
[1])
786 /* ignore this match and search the next one */
787 return g_match_info_next (match_info
, error
);
790 return match_info
->matches
>= 0;
794 * g_match_info_matches:
795 * @match_info: a #GMatchInfo structure
797 * Returns whether the previous match operation succeeded.
799 * Returns: %TRUE if the previous match operation succeeded,
805 g_match_info_matches (const GMatchInfo
*match_info
)
807 g_return_val_if_fail (match_info
!= NULL
, FALSE
);
809 return match_info
->matches
>= 0;
813 * g_match_info_get_match_count:
814 * @match_info: a #GMatchInfo structure
816 * Retrieves the number of matched substrings (including substring 0,
817 * that is the whole matched text), so 1 is returned if the pattern
818 * has no substrings in it and 0 is returned if the match failed.
820 * If the last match was obtained using the DFA algorithm, that is
821 * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
822 * count is not that of the number of capturing parentheses but that of
823 * the number of matched substrings.
825 * Returns: Number of matched substrings, or -1 if an error occurred
830 g_match_info_get_match_count (const GMatchInfo
*match_info
)
832 g_return_val_if_fail (match_info
, -1);
834 if (match_info
->matches
== PCRE_ERROR_NOMATCH
)
837 else if (match_info
->matches
< PCRE_ERROR_NOMATCH
)
842 return match_info
->matches
;
846 * g_match_info_is_partial_match:
847 * @match_info: a #GMatchInfo structure
849 * Usually if the string passed to g_regex_match*() matches as far as
850 * it goes, but is too short to match the entire pattern, %FALSE is
851 * returned. There are circumstances where it might be helpful to
852 * distinguish this case from other cases in which there is no match.
854 * Consider, for example, an application where a human is required to
855 * type in data for a field with specific formatting requirements. An
856 * example might be a date in the form ddmmmyy, defined by the pattern
857 * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
858 * If the application sees the user’s keystrokes one by one, and can
859 * check that what has been typed so far is potentially valid, it is
860 * able to raise an error as soon as a mistake is made.
862 * GRegex supports the concept of partial matching by means of the
863 * #G_REGEX_MATCH_PARTIAL_SOFT and #G_REGEX_MATCH_PARTIAL_HARD flags.
864 * When they are used, the return code for
865 * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
866 * for a complete match, %FALSE otherwise. But, when these functions
867 * return %FALSE, you can check if the match was partial calling
868 * g_match_info_is_partial_match().
870 * The difference between #G_REGEX_MATCH_PARTIAL_SOFT and
871 * #G_REGEX_MATCH_PARTIAL_HARD is that when a partial match is encountered
872 * with #G_REGEX_MATCH_PARTIAL_SOFT, matching continues to search for a
873 * possible complete match, while with #G_REGEX_MATCH_PARTIAL_HARD matching
874 * stops at the partial match.
875 * When both #G_REGEX_MATCH_PARTIAL_SOFT and #G_REGEX_MATCH_PARTIAL_HARD
876 * are set, the latter takes precedence.
877 * See <ulink>man:pcrepartial</ulink> for more information on partial matching.
879 * Because of the way certain internal optimizations are implemented
880 * the partial matching algorithm cannot be used with all patterns.
881 * So repeated single characters such as "a{2,4}" and repeated single
882 * meta-sequences such as "\d+" are not permitted if the maximum number
883 * of occurrences is greater than one. Optional items such as "\d?"
884 * (where the maximum is one) are permitted. Quantifiers with any values
885 * are permitted after parentheses, so the invalid examples above can be
886 * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL or
887 * #G_REGEX_MATCH_PARTIAL_HARD is set
888 * for a pattern that does not conform to the restrictions, matching
889 * functions return an error.
891 * Returns: %TRUE if the match was partial, %FALSE otherwise
896 g_match_info_is_partial_match (const GMatchInfo
*match_info
)
898 g_return_val_if_fail (match_info
!= NULL
, FALSE
);
900 return match_info
->matches
== PCRE_ERROR_PARTIAL
;
904 * g_match_info_expand_references:
905 * @match_info: (allow-none): a #GMatchInfo or %NULL
906 * @string_to_expand: the string to expand
907 * @error: location to store the error occurring, or %NULL to ignore errors
909 * Returns a new string containing the text in @string_to_expand with
910 * references and escape sequences expanded. References refer to the last
911 * match done with @string against @regex and have the same syntax used by
914 * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
915 * passed to g_regex_new().
917 * The backreferences are extracted from the string passed to the match
918 * function, so you cannot call this function after freeing the string.
920 * @match_info may be %NULL in which case @string_to_expand must not
921 * contain references. For instance "foo\n" does not refer to an actual
922 * pattern and '\n' merely will be replaced with \n character,
923 * while to expand "\0" (whole match) one needs the result of a match.
924 * Use g_regex_check_replacement() to find out whether @string_to_expand
925 * contains references.
927 * Returns: (allow-none): the expanded string, or %NULL if an error occurred
932 g_match_info_expand_references (const GMatchInfo
*match_info
,
933 const gchar
*string_to_expand
,
938 GError
*tmp_error
= NULL
;
940 g_return_val_if_fail (string_to_expand
!= NULL
, NULL
);
941 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
943 list
= split_replacement (string_to_expand
, &tmp_error
);
944 if (tmp_error
!= NULL
)
946 g_propagate_error (error
, tmp_error
);
950 if (!match_info
&& interpolation_list_needs_match (list
))
952 g_critical ("String '%s' contains references to the match, can't "
953 "expand references without GMatchInfo object",
958 result
= g_string_sized_new (strlen (string_to_expand
));
959 interpolate_replacement (match_info
, result
, list
);
961 g_list_free_full (list
, (GDestroyNotify
) free_interpolation_data
);
963 return g_string_free (result
, FALSE
);
967 * g_match_info_fetch:
968 * @match_info: #GMatchInfo structure
969 * @match_num: number of the sub expression
971 * Retrieves the text matching the @match_num<!-- -->'th capturing
972 * parentheses. 0 is the full text of the match, 1 is the first paren
973 * set, 2 the second, and so on.
975 * If @match_num is a valid sub pattern but it didn't match anything
976 * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
977 * string is returned.
979 * If the match was obtained using the DFA algorithm, that is using
980 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
981 * string is not that of a set of parentheses but that of a matched
982 * substring. Substrings are matched in reverse order of length, so
983 * 0 is the longest match.
985 * The string is fetched from the string passed to the match function,
986 * so you cannot call this function after freeing the string.
988 * Returns: (allow-none): The matched substring, or %NULL if an error
989 * occurred. You have to free the string yourself
994 g_match_info_fetch (const GMatchInfo
*match_info
,
997 /* we cannot use pcre_get_substring() because it allocates the
998 * string using pcre_malloc(). */
1002 g_return_val_if_fail (match_info
!= NULL
, NULL
);
1003 g_return_val_if_fail (match_num
>= 0, NULL
);
1005 /* match_num does not exist or it didn't matched, i.e. matching "b"
1006 * against "(a)?b" then group 0 is empty. */
1007 if (!g_match_info_fetch_pos (match_info
, match_num
, &start
, &end
))
1009 else if (start
== -1)
1010 match
= g_strdup ("");
1012 match
= g_strndup (&match_info
->string
[start
], end
- start
);
1018 * g_match_info_fetch_pos:
1019 * @match_info: #GMatchInfo structure
1020 * @match_num: number of the sub expression
1021 * @start_pos: (out) (allow-none): pointer to location where to store
1022 * the start position, or %NULL
1023 * @end_pos: (out) (allow-none): pointer to location where to store
1024 * the end position, or %NULL
1026 * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
1027 * parentheses. 0 is the full text of the match, 1 is the first
1028 * paren set, 2 the second, and so on.
1030 * If @match_num is a valid sub pattern but it didn't match anything
1031 * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
1032 * and @end_pos are set to -1 and %TRUE is returned.
1034 * If the match was obtained using the DFA algorithm, that is using
1035 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1036 * position is not that of a set of parentheses but that of a matched
1037 * substring. Substrings are matched in reverse order of length, so
1038 * 0 is the longest match.
1040 * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
1041 * the position cannot be fetched, @start_pos and @end_pos are left
1047 g_match_info_fetch_pos (const GMatchInfo
*match_info
,
1052 g_return_val_if_fail (match_info
!= NULL
, FALSE
);
1053 g_return_val_if_fail (match_num
>= 0, FALSE
);
1055 /* make sure the sub expression number they're requesting is less than
1056 * the total number of sub expressions that were matched. */
1057 if (match_num
>= match_info
->matches
)
1060 if (start_pos
!= NULL
)
1061 *start_pos
= match_info
->offsets
[2 * match_num
];
1063 if (end_pos
!= NULL
)
1064 *end_pos
= match_info
->offsets
[2 * match_num
+ 1];
1070 * Returns number of first matched subpattern with name @name.
1071 * There may be more than one in case when DUPNAMES is used,
1072 * and not all subpatterns with that name match;
1073 * pcre_get_stringnumber() does not work in that case.
1076 get_matched_substring_number (const GMatchInfo
*match_info
,
1080 gchar
*first
, *last
;
1083 if (!(match_info
->regex
->compile_opts
& G_REGEX_DUPNAMES
))
1084 return pcre_get_stringnumber (match_info
->regex
->pcre_re
, name
);
1086 /* This code is copied from pcre_get.c: get_first_set() */
1087 entrysize
= pcre_get_stringtable_entries (match_info
->regex
->pcre_re
,
1095 for (entry
= (guchar
*) first
; entry
<= (guchar
*) last
; entry
+= entrysize
)
1097 gint n
= (entry
[0] << 8) + entry
[1];
1098 if (match_info
->offsets
[n
*2] >= 0)
1102 return (first
[0] << 8) + first
[1];
1106 * g_match_info_fetch_named:
1107 * @match_info: #GMatchInfo structure
1108 * @name: name of the subexpression
1110 * Retrieves the text matching the capturing parentheses named @name.
1112 * If @name is a valid sub pattern name but it didn't match anything
1113 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1114 * then an empty string is returned.
1116 * The string is fetched from the string passed to the match function,
1117 * so you cannot call this function after freeing the string.
1119 * Returns: (allow-none): The matched substring, or %NULL if an error
1120 * occurred. You have to free the string yourself
1125 g_match_info_fetch_named (const GMatchInfo
*match_info
,
1128 /* we cannot use pcre_get_named_substring() because it allocates the
1129 * string using pcre_malloc(). */
1132 g_return_val_if_fail (match_info
!= NULL
, NULL
);
1133 g_return_val_if_fail (name
!= NULL
, NULL
);
1135 num
= get_matched_substring_number (match_info
, name
);
1139 return g_match_info_fetch (match_info
, num
);
1143 * g_match_info_fetch_named_pos:
1144 * @match_info: #GMatchInfo structure
1145 * @name: name of the subexpression
1146 * @start_pos: (out) (allow-none): pointer to location where to store
1147 * the start position, or %NULL
1148 * @end_pos: (out) (allow-none): pointer to location where to store
1149 * the end position, or %NULL
1151 * Retrieves the position in bytes of the capturing parentheses named @name.
1153 * If @name is a valid sub pattern name but it didn't match anything
1154 * (e.g. sub pattern "X", matching "b" against "(?P<X>a)?b")
1155 * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
1157 * Returns: %TRUE if the position was fetched, %FALSE otherwise.
1158 * If the position cannot be fetched, @start_pos and @end_pos
1159 * are left unchanged.
1164 g_match_info_fetch_named_pos (const GMatchInfo
*match_info
,
1171 g_return_val_if_fail (match_info
!= NULL
, FALSE
);
1172 g_return_val_if_fail (name
!= NULL
, FALSE
);
1174 num
= get_matched_substring_number (match_info
, name
);
1178 return g_match_info_fetch_pos (match_info
, num
, start_pos
, end_pos
);
1182 * g_match_info_fetch_all:
1183 * @match_info: a #GMatchInfo structure
1185 * Bundles up pointers to each of the matching substrings from a match
1186 * and stores them in an array of gchar pointers. The first element in
1187 * the returned array is the match number 0, i.e. the entire matched
1190 * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
1191 * "b" against "(a)?b") then an empty string is inserted.
1193 * If the last match was obtained using the DFA algorithm, that is using
1194 * g_regex_match_all() or g_regex_match_all_full(), the retrieved
1195 * strings are not that matched by sets of parentheses but that of the
1196 * matched substring. Substrings are matched in reverse order of length,
1197 * so the first one is the longest match.
1199 * The strings are fetched from the string passed to the match function,
1200 * so you cannot call this function after freeing the string.
1202 * Returns: (transfer full): a %NULL-terminated array of gchar *
1203 * pointers. It must be freed using g_strfreev(). If the previous
1204 * match failed %NULL is returned
1209 g_match_info_fetch_all (const GMatchInfo
*match_info
)
1211 /* we cannot use pcre_get_substring_list() because the returned value
1212 * isn't suitable for g_strfreev(). */
1216 g_return_val_if_fail (match_info
!= NULL
, NULL
);
1218 if (match_info
->matches
< 0)
1221 result
= g_new (gchar
*, match_info
->matches
+ 1);
1222 for (i
= 0; i
< match_info
->matches
; i
++)
1223 result
[i
] = g_match_info_fetch (match_info
, i
);
1232 G_DEFINE_QUARK (g
-regex
-error
-quark
, g_regex_error
)
1238 * Increases reference count of @regex by 1.
1245 g_regex_ref (GRegex
*regex
)
1247 g_return_val_if_fail (regex
!= NULL
, NULL
);
1248 g_atomic_int_inc (®ex
->ref_count
);
1256 * Decreases reference count of @regex by 1. When reference count drops
1257 * to zero, it frees all the memory associated with the regex structure.
1262 g_regex_unref (GRegex
*regex
)
1264 g_return_if_fail (regex
!= NULL
);
1266 if (g_atomic_int_dec_and_test (®ex
->ref_count
))
1268 g_free (regex
->pattern
);
1269 if (regex
->pcre_re
!= NULL
)
1270 pcre_free (regex
->pcre_re
);
1271 if (regex
->extra
!= NULL
)
1272 pcre_free (regex
->extra
);
1279 * @pattern: the regular expression
1280 * @compile_options: compile options for the regular expression, or 0
1281 * @match_options: match options for the regular expression, or 0
1282 * @error: return location for a #GError
1284 * Compiles the regular expression to an internal form, and does
1285 * the initial setup of the #GRegex structure.
1287 * Returns: a #GRegex structure. Call g_regex_unref() when you
1293 g_regex_new (const gchar
*pattern
,
1294 GRegexCompileFlags compile_options
,
1295 GRegexMatchFlags match_options
,
1300 const gchar
*errmsg
;
1303 gboolean optimize
= FALSE
;
1304 static volatile gsize initialised
= 0;
1305 unsigned long int pcre_compile_options
;
1306 GRegexCompileFlags nonpcre_compile_options
;
1308 g_return_val_if_fail (pattern
!= NULL
, NULL
);
1309 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
1310 g_return_val_if_fail ((compile_options
& ~G_REGEX_COMPILE_MASK
) == 0, NULL
);
1311 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, NULL
);
1313 if (g_once_init_enter (&initialised
))
1315 int supports_utf8
, supports_ucp
;
1317 pcre_config (PCRE_CONFIG_UTF8
, &supports_utf8
);
1319 g_critical (_("PCRE library is compiled without UTF8 support"));
1321 pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES
, &supports_ucp
);
1323 g_critical (_("PCRE library is compiled without UTF8 properties support"));
1325 g_once_init_leave (&initialised
, supports_utf8
&& supports_ucp
? 1 : 2);
1328 if (G_UNLIKELY (initialised
!= 1))
1330 g_set_error_literal (error
, G_REGEX_ERROR
, G_REGEX_ERROR_COMPILE
,
1331 _("PCRE library is compiled with incompatible options"));
1335 nonpcre_compile_options
= compile_options
& G_REGEX_COMPILE_NONPCRE_MASK
;
1337 /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
1338 * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
1339 if (compile_options
& G_REGEX_OPTIMIZE
)
1342 /* In GRegex the string are, by default, UTF-8 encoded. PCRE
1343 * instead uses UTF-8 only if required with PCRE_UTF8. */
1344 if (compile_options
& G_REGEX_RAW
)
1347 compile_options
&= ~G_REGEX_RAW
;
1352 compile_options
|= PCRE_UTF8
| PCRE_NO_UTF8_CHECK
;
1353 match_options
|= PCRE_NO_UTF8_CHECK
;
1356 /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
1357 * not for the system one. */
1358 if (!(compile_options
& G_REGEX_NEWLINE_CR
) &&
1359 !(compile_options
& G_REGEX_NEWLINE_LF
))
1361 compile_options
|= PCRE_NEWLINE_ANY
;
1364 compile_options
|= PCRE_UCP
;
1366 /* PCRE_BSR_UNICODE is the default for the internal PCRE but
1367 * possibly not for the system one.
1369 if (~compile_options
& G_REGEX_BSR_ANYCRLF
)
1370 compile_options
|= PCRE_BSR_UNICODE
;
1372 /* compile the pattern */
1373 re
= pcre_compile2 (pattern
, compile_options
, &errcode
,
1374 &errmsg
, &erroffset
, NULL
);
1376 /* if the compilation failed, set the error member and return
1382 /* Translate the PCRE error code to GRegexError and use a translated
1383 * error message if possible */
1384 translate_compile_error (&errcode
, &errmsg
);
1386 /* PCRE uses byte offsets but we want to show character offsets */
1387 erroffset
= g_utf8_pointer_to_offset (pattern
, &pattern
[erroffset
]);
1389 tmp_error
= g_error_new (G_REGEX_ERROR
, errcode
,
1390 _("Error while compiling regular "
1391 "expression %s at char %d: %s"),
1392 pattern
, erroffset
, errmsg
);
1393 g_propagate_error (error
, tmp_error
);
1398 /* For options set at the beginning of the pattern, pcre puts them into
1399 * compile options, e.g. "(?i)foo" will make the pcre structure store
1400 * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
1401 pcre_fullinfo (re
, NULL
, PCRE_INFO_OPTIONS
, &pcre_compile_options
);
1402 compile_options
= pcre_compile_options
& G_REGEX_COMPILE_PCRE_MASK
;
1404 /* Don't leak PCRE_NEWLINE_ANY, which is part of PCRE_NEWLINE_ANYCRLF */
1405 if ((pcre_compile_options
& PCRE_NEWLINE_ANYCRLF
) != PCRE_NEWLINE_ANYCRLF
)
1406 compile_options
&= ~PCRE_NEWLINE_ANY
;
1408 compile_options
|= nonpcre_compile_options
;
1410 if (!(compile_options
& G_REGEX_DUPNAMES
))
1412 gboolean jchanged
= FALSE
;
1413 pcre_fullinfo (re
, NULL
, PCRE_INFO_JCHANGED
, &jchanged
);
1415 compile_options
|= G_REGEX_DUPNAMES
;
1418 regex
= g_new0 (GRegex
, 1);
1419 regex
->ref_count
= 1;
1420 regex
->pattern
= g_strdup (pattern
);
1421 regex
->pcre_re
= re
;
1422 regex
->compile_opts
= compile_options
;
1423 regex
->match_opts
= match_options
;
1427 regex
->extra
= pcre_study (regex
->pcre_re
, 0, &errmsg
);
1430 GError
*tmp_error
= g_error_new (G_REGEX_ERROR
,
1431 G_REGEX_ERROR_OPTIMIZE
,
1432 _("Error while optimizing "
1433 "regular expression %s: %s"),
1436 g_propagate_error (error
, tmp_error
);
1438 g_regex_unref (regex
);
1447 * g_regex_get_pattern:
1448 * @regex: a #GRegex structure
1450 * Gets the pattern string associated with @regex, i.e. a copy of
1451 * the string passed to g_regex_new().
1453 * Returns: the pattern of @regex
1458 g_regex_get_pattern (const GRegex
*regex
)
1460 g_return_val_if_fail (regex
!= NULL
, NULL
);
1462 return regex
->pattern
;
1466 * g_regex_get_max_backref:
1469 * Returns the number of the highest back reference
1470 * in the pattern, or 0 if the pattern does not contain
1473 * Returns: the number of the highest back reference
1478 g_regex_get_max_backref (const GRegex
*regex
)
1482 pcre_fullinfo (regex
->pcre_re
, regex
->extra
,
1483 PCRE_INFO_BACKREFMAX
, &value
);
1489 * g_regex_get_capture_count:
1492 * Returns the number of capturing subpatterns in the pattern.
1494 * Returns: the number of capturing subpatterns
1499 g_regex_get_capture_count (const GRegex
*regex
)
1503 pcre_fullinfo (regex
->pcre_re
, regex
->extra
,
1504 PCRE_INFO_CAPTURECOUNT
, &value
);
1510 * g_regex_get_has_cr_or_lf:
1511 * @regex: a #GRegex structure
1513 * Checks whether the pattern contains explicit CR or LF references.
1515 * Returns: %TRUE if the pattern contains explicit CR or LF references
1520 g_regex_get_has_cr_or_lf (const GRegex
*regex
)
1524 pcre_fullinfo (regex
->pcre_re
, regex
->extra
,
1525 PCRE_INFO_HASCRORLF
, &value
);
1531 * g_regex_get_compile_flags:
1534 * Returns the compile options that @regex was created with.
1536 * Returns: flags from #GRegexCompileFlags
1541 g_regex_get_compile_flags (const GRegex
*regex
)
1543 g_return_val_if_fail (regex
!= NULL
, 0);
1545 return regex
->compile_opts
;
1549 * g_regex_get_match_flags:
1552 * Returns the match options that @regex was created with.
1554 * Returns: flags from #GRegexMatchFlags
1559 g_regex_get_match_flags (const GRegex
*regex
)
1561 g_return_val_if_fail (regex
!= NULL
, 0);
1563 return regex
->match_opts
& G_REGEX_MATCH_MASK
;
1567 * g_regex_match_simple:
1568 * @pattern: the regular expression
1569 * @string: the string to scan for matches
1570 * @compile_options: compile options for the regular expression, or 0
1571 * @match_options: match options, or 0
1573 * Scans for a match in @string for @pattern.
1575 * This function is equivalent to g_regex_match() but it does not
1576 * require to compile the pattern with g_regex_new(), avoiding some
1577 * lines of code when you need just to do a match without extracting
1578 * substrings, capture counts, and so on.
1580 * If this function is to be called on the same @pattern more than
1581 * once, it's more efficient to compile the pattern once with
1582 * g_regex_new() and then use g_regex_match().
1584 * Returns: %TRUE if the string matched, %FALSE otherwise
1589 g_regex_match_simple (const gchar
*pattern
,
1590 const gchar
*string
,
1591 GRegexCompileFlags compile_options
,
1592 GRegexMatchFlags match_options
)
1597 regex
= g_regex_new (pattern
, compile_options
, 0, NULL
);
1600 result
= g_regex_match_full (regex
, string
, -1, 0, match_options
, NULL
, NULL
);
1601 g_regex_unref (regex
);
1607 * @regex: a #GRegex structure from g_regex_new()
1608 * @string: the string to scan for matches
1609 * @match_options: match options
1610 * @match_info: (out) (allow-none): pointer to location where to store
1611 * the #GMatchInfo, or %NULL if you do not need it
1613 * Scans for a match in string for the pattern in @regex.
1614 * The @match_options are combined with the match options specified
1615 * when the @regex structure was created, letting you have more
1616 * flexibility in reusing #GRegex structures.
1618 * A #GMatchInfo structure, used to get information on the match,
1619 * is stored in @match_info if not %NULL. Note that if @match_info
1620 * is not %NULL then it is created even if the function returns %FALSE,
1621 * i.e. you must free it regardless if regular expression actually matched.
1623 * To retrieve all the non-overlapping matches of the pattern in
1624 * string you can use g_match_info_next().
1628 * print_uppercase_words (const gchar *string)
1630 * /* Print all uppercase-only words. */
1632 * GMatchInfo *match_info;
1634 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1635 * g_regex_match (regex, string, 0, &match_info);
1636 * while (g_match_info_matches (match_info))
1638 * gchar *word = g_match_info_fetch (match_info, 0);
1639 * g_print ("Found: %s\n", word);
1641 * g_match_info_next (match_info, NULL);
1643 * g_match_info_free (match_info);
1644 * g_regex_unref (regex);
1648 * @string is not copied and is used in #GMatchInfo internally. If
1649 * you use any #GMatchInfo method (except g_match_info_free()) after
1650 * freeing or modifying @string then the behaviour is undefined.
1652 * Returns: %TRUE is the string matched, %FALSE otherwise
1657 g_regex_match (const GRegex
*regex
,
1658 const gchar
*string
,
1659 GRegexMatchFlags match_options
,
1660 GMatchInfo
**match_info
)
1662 return g_regex_match_full (regex
, string
, -1, 0, match_options
,
1667 * g_regex_match_full:
1668 * @regex: a #GRegex structure from g_regex_new()
1669 * @string: (array length=string_len): the string to scan for matches
1670 * @string_len: the length of @string, or -1 if @string is nul-terminated
1671 * @start_position: starting index of the string to match
1672 * @match_options: match options
1673 * @match_info: (out) (allow-none): pointer to location where to store
1674 * the #GMatchInfo, or %NULL if you do not need it
1675 * @error: location to store the error occurring, or %NULL to ignore errors
1677 * Scans for a match in string for the pattern in @regex.
1678 * The @match_options are combined with the match options specified
1679 * when the @regex structure was created, letting you have more
1680 * flexibility in reusing #GRegex structures.
1682 * Setting @start_position differs from just passing over a shortened
1683 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1684 * that begins with any kind of lookbehind assertion, such as "\b".
1686 * A #GMatchInfo structure, used to get information on the match, is
1687 * stored in @match_info if not %NULL. Note that if @match_info is
1688 * not %NULL then it is created even if the function returns %FALSE,
1689 * i.e. you must free it regardless if regular expression actually
1692 * @string is not copied and is used in #GMatchInfo internally. If
1693 * you use any #GMatchInfo method (except g_match_info_free()) after
1694 * freeing or modifying @string then the behaviour is undefined.
1696 * To retrieve all the non-overlapping matches of the pattern in
1697 * string you can use g_match_info_next().
1701 * print_uppercase_words (const gchar *string)
1703 * /* Print all uppercase-only words. */
1705 * GMatchInfo *match_info;
1706 * GError *error = NULL;
1708 * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
1709 * g_regex_match_full (regex, string, -1, 0, 0, &match_info, &error);
1710 * while (g_match_info_matches (match_info))
1712 * gchar *word = g_match_info_fetch (match_info, 0);
1713 * g_print ("Found: %s\n", word);
1715 * g_match_info_next (match_info, &error);
1717 * g_match_info_free (match_info);
1718 * g_regex_unref (regex);
1719 * if (error != NULL)
1721 * g_printerr ("Error while matching: %s\n", error->message);
1722 * g_error_free (error);
1727 * Returns: %TRUE is the string matched, %FALSE otherwise
1732 g_regex_match_full (const GRegex
*regex
,
1733 const gchar
*string
,
1735 gint start_position
,
1736 GRegexMatchFlags match_options
,
1737 GMatchInfo
**match_info
,
1743 g_return_val_if_fail (regex
!= NULL
, FALSE
);
1744 g_return_val_if_fail (string
!= NULL
, FALSE
);
1745 g_return_val_if_fail (start_position
>= 0, FALSE
);
1746 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
1747 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, FALSE
);
1749 info
= match_info_new (regex
, string
, string_len
, start_position
,
1750 match_options
, FALSE
);
1751 match_ok
= g_match_info_next (info
, error
);
1752 if (match_info
!= NULL
)
1755 g_match_info_free (info
);
1761 * g_regex_match_all:
1762 * @regex: a #GRegex structure from g_regex_new()
1763 * @string: the string to scan for matches
1764 * @match_options: match options
1765 * @match_info: (out) (allow-none): pointer to location where to store
1766 * the #GMatchInfo, or %NULL if you do not need it
1768 * Using the standard algorithm for regular expression matching only
1769 * the longest match in the string is retrieved. This function uses
1770 * a different algorithm so it can retrieve all the possible matches.
1771 * For more documentation see g_regex_match_all_full().
1773 * A #GMatchInfo structure, used to get information on the match, is
1774 * stored in @match_info if not %NULL. Note that if @match_info is
1775 * not %NULL then it is created even if the function returns %FALSE,
1776 * i.e. you must free it regardless if regular expression actually
1779 * @string is not copied and is used in #GMatchInfo internally. If
1780 * you use any #GMatchInfo method (except g_match_info_free()) after
1781 * freeing or modifying @string then the behaviour is undefined.
1783 * Returns: %TRUE is the string matched, %FALSE otherwise
1788 g_regex_match_all (const GRegex
*regex
,
1789 const gchar
*string
,
1790 GRegexMatchFlags match_options
,
1791 GMatchInfo
**match_info
)
1793 return g_regex_match_all_full (regex
, string
, -1, 0, match_options
,
1798 * g_regex_match_all_full:
1799 * @regex: a #GRegex structure from g_regex_new()
1800 * @string: (array length=string_len): the string to scan for matches
1801 * @string_len: the length of @string, or -1 if @string is nul-terminated
1802 * @start_position: starting index of the string to match
1803 * @match_options: match options
1804 * @match_info: (out) (allow-none): pointer to location where to store
1805 * the #GMatchInfo, or %NULL if you do not need it
1806 * @error: location to store the error occurring, or %NULL to ignore errors
1808 * Using the standard algorithm for regular expression matching only
1809 * the longest match in the string is retrieved, it is not possible
1810 * to obtain all the available matches. For instance matching
1811 * "<a> <b> <c>" against the pattern "<.*>"
1812 * you get "<a> <b> <c>".
1814 * This function uses a different algorithm (called DFA, i.e. deterministic
1815 * finite automaton), so it can retrieve all the possible matches, all
1816 * starting at the same point in the string. For instance matching
1817 * "<a> <b> <c>" against the pattern "<.*>"
1818 * you would obtain three matches: "<a> <b> <c>",
1819 * "<a> <b>" and "<a>".
1821 * The number of matched strings is retrieved using
1822 * g_match_info_get_match_count(). To obtain the matched strings and
1823 * their position you can use, respectively, g_match_info_fetch() and
1824 * g_match_info_fetch_pos(). Note that the strings are returned in
1825 * reverse order of length; that is, the longest matching string is
1828 * Note that the DFA algorithm is slower than the standard one and it
1829 * is not able to capture substrings, so backreferences do not work.
1831 * Setting @start_position differs from just passing over a shortened
1832 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
1833 * that begins with any kind of lookbehind assertion, such as "\b".
1835 * A #GMatchInfo structure, used to get information on the match, is
1836 * stored in @match_info if not %NULL. Note that if @match_info is
1837 * not %NULL then it is created even if the function returns %FALSE,
1838 * i.e. you must free it regardless if regular expression actually
1841 * @string is not copied and is used in #GMatchInfo internally. If
1842 * you use any #GMatchInfo method (except g_match_info_free()) after
1843 * freeing or modifying @string then the behaviour is undefined.
1845 * Returns: %TRUE is the string matched, %FALSE otherwise
1850 g_regex_match_all_full (const GRegex
*regex
,
1851 const gchar
*string
,
1853 gint start_position
,
1854 GRegexMatchFlags match_options
,
1855 GMatchInfo
**match_info
,
1861 g_return_val_if_fail (regex
!= NULL
, FALSE
);
1862 g_return_val_if_fail (string
!= NULL
, FALSE
);
1863 g_return_val_if_fail (start_position
>= 0, FALSE
);
1864 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
1865 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, FALSE
);
1867 info
= match_info_new (regex
, string
, string_len
, start_position
,
1868 match_options
, TRUE
);
1874 info
->matches
= pcre_dfa_exec (regex
->pcre_re
, regex
->extra
,
1875 info
->string
, info
->string_len
,
1877 regex
->match_opts
| match_options
,
1878 info
->offsets
, info
->n_offsets
,
1879 info
->workspace
, info
->n_workspace
);
1880 if (info
->matches
== PCRE_ERROR_DFA_WSSIZE
)
1882 /* info->workspace is too small. */
1883 info
->n_workspace
*= 2;
1884 info
->workspace
= g_realloc (info
->workspace
,
1885 info
->n_workspace
* sizeof (gint
));
1888 else if (info
->matches
== 0)
1890 /* info->offsets is too small. */
1891 info
->n_offsets
*= 2;
1892 info
->offsets
= g_realloc (info
->offsets
,
1893 info
->n_offsets
* sizeof (gint
));
1896 else if (IS_PCRE_ERROR (info
->matches
))
1898 g_set_error (error
, G_REGEX_ERROR
, G_REGEX_ERROR_MATCH
,
1899 _("Error while matching regular expression %s: %s"),
1900 regex
->pattern
, match_error (info
->matches
));
1904 /* set info->pos to -1 so that a call to g_match_info_next() fails. */
1907 if (match_info
!= NULL
)
1910 g_match_info_free (info
);
1912 return info
->matches
>= 0;
1916 * g_regex_get_string_number:
1917 * @regex: #GRegex structure
1918 * @name: name of the subexpression
1920 * Retrieves the number of the subexpression named @name.
1922 * Returns: The number of the subexpression or -1 if @name
1928 g_regex_get_string_number (const GRegex
*regex
,
1933 g_return_val_if_fail (regex
!= NULL
, -1);
1934 g_return_val_if_fail (name
!= NULL
, -1);
1936 num
= pcre_get_stringnumber (regex
->pcre_re
, name
);
1937 if (num
== PCRE_ERROR_NOSUBSTRING
)
1944 * g_regex_split_simple:
1945 * @pattern: the regular expression
1946 * @string: the string to scan for matches
1947 * @compile_options: compile options for the regular expression, or 0
1948 * @match_options: match options, or 0
1950 * Breaks the string on the pattern, and returns an array of
1951 * the tokens. If the pattern contains capturing parentheses,
1952 * then the text for each of the substrings will also be returned.
1953 * If the pattern does not match anywhere in the string, then the
1954 * whole string is returned as the first token.
1956 * This function is equivalent to g_regex_split() but it does
1957 * not require to compile the pattern with g_regex_new(), avoiding
1958 * some lines of code when you need just to do a split without
1959 * extracting substrings, capture counts, and so on.
1961 * If this function is to be called on the same @pattern more than
1962 * once, it's more efficient to compile the pattern once with
1963 * g_regex_new() and then use g_regex_split().
1965 * As a special case, the result of splitting the empty string ""
1966 * is an empty vector, not a vector containing a single string.
1967 * The reason for this special case is that being able to represent
1968 * a empty vector is typically more useful than consistent handling
1969 * of empty elements. If you do need to represent empty elements,
1970 * you'll need to check for the empty string before calling this
1973 * A pattern that can match empty strings splits @string into
1974 * separate characters wherever it matches the empty string between
1975 * characters. For example splitting "ab c" using as a separator
1976 * "\s*", you will get "a", "b" and "c".
1978 * Returns: (transfer full): a %NULL-terminated array of strings. Free
1979 * it using g_strfreev()
1984 g_regex_split_simple (const gchar
*pattern
,
1985 const gchar
*string
,
1986 GRegexCompileFlags compile_options
,
1987 GRegexMatchFlags match_options
)
1992 regex
= g_regex_new (pattern
, compile_options
, 0, NULL
);
1996 result
= g_regex_split_full (regex
, string
, -1, 0, match_options
, 0, NULL
);
1997 g_regex_unref (regex
);
2003 * @regex: a #GRegex structure
2004 * @string: the string to split with the pattern
2005 * @match_options: match time option flags
2007 * Breaks the string on the pattern, and returns an array of the tokens.
2008 * If the pattern contains capturing parentheses, then the text for each
2009 * of the substrings will also be returned. If the pattern does not match
2010 * anywhere in the string, then the whole string is returned as the first
2013 * As a special case, the result of splitting the empty string "" is an
2014 * empty vector, not a vector containing a single string. The reason for
2015 * this special case is that being able to represent a empty vector is
2016 * typically more useful than consistent handling of empty elements. If
2017 * you do need to represent empty elements, you'll need to check for the
2018 * empty string before calling this function.
2020 * A pattern that can match empty strings splits @string into separate
2021 * characters wherever it matches the empty string between characters.
2022 * For example splitting "ab c" using as a separator "\s*", you will get
2025 * Returns: (transfer full): a %NULL-terminated gchar ** array. Free
2026 * it using g_strfreev()
2031 g_regex_split (const GRegex
*regex
,
2032 const gchar
*string
,
2033 GRegexMatchFlags match_options
)
2035 return g_regex_split_full (regex
, string
, -1, 0,
2036 match_options
, 0, NULL
);
2040 * g_regex_split_full:
2041 * @regex: a #GRegex structure
2042 * @string: (array length=string_len): the string to split with the pattern
2043 * @string_len: the length of @string, or -1 if @string is nul-terminated
2044 * @start_position: starting index of the string to match
2045 * @match_options: match time option flags
2046 * @max_tokens: the maximum number of tokens to split @string into.
2047 * If this is less than 1, the string is split completely
2048 * @error: return location for a #GError
2050 * Breaks the string on the pattern, and returns an array of the tokens.
2051 * If the pattern contains capturing parentheses, then the text for each
2052 * of the substrings will also be returned. If the pattern does not match
2053 * anywhere in the string, then the whole string is returned as the first
2056 * As a special case, the result of splitting the empty string "" is an
2057 * empty vector, not a vector containing a single string. The reason for
2058 * this special case is that being able to represent a empty vector is
2059 * typically more useful than consistent handling of empty elements. If
2060 * you do need to represent empty elements, you'll need to check for the
2061 * empty string before calling this function.
2063 * A pattern that can match empty strings splits @string into separate
2064 * characters wherever it matches the empty string between characters.
2065 * For example splitting "ab c" using as a separator "\s*", you will get
2068 * Setting @start_position differs from just passing over a shortened
2069 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2070 * that begins with any kind of lookbehind assertion, such as "\b".
2072 * Returns: (transfer full): a %NULL-terminated gchar ** array. Free
2073 * it using g_strfreev()
2078 g_regex_split_full (const GRegex
*regex
,
2079 const gchar
*string
,
2081 gint start_position
,
2082 GRegexMatchFlags match_options
,
2086 GError
*tmp_error
= NULL
;
2087 GMatchInfo
*match_info
;
2092 /* position of the last separator. */
2093 gint last_separator_end
;
2094 /* was the last match 0 bytes long? */
2095 gboolean last_match_is_empty
;
2096 /* the returned array of char **s */
2097 gchar
**string_list
;
2099 g_return_val_if_fail (regex
!= NULL
, NULL
);
2100 g_return_val_if_fail (string
!= NULL
, NULL
);
2101 g_return_val_if_fail (start_position
>= 0, NULL
);
2102 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
2103 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, NULL
);
2105 if (max_tokens
<= 0)
2106 max_tokens
= G_MAXINT
;
2109 string_len
= strlen (string
);
2111 /* zero-length string */
2112 if (string_len
- start_position
== 0)
2113 return g_new0 (gchar
*, 1);
2115 if (max_tokens
== 1)
2117 string_list
= g_new0 (gchar
*, 2);
2118 string_list
[0] = g_strndup (&string
[start_position
],
2119 string_len
- start_position
);
2125 last_separator_end
= start_position
;
2126 last_match_is_empty
= FALSE
;
2128 match_ok
= g_regex_match_full (regex
, string
, string_len
, start_position
,
2129 match_options
, &match_info
, &tmp_error
);
2131 while (tmp_error
== NULL
)
2135 last_match_is_empty
=
2136 (match_info
->offsets
[0] == match_info
->offsets
[1]);
2138 /* we need to skip empty separators at the same position of the end
2139 * of another separator. e.g. the string is "a b" and the separator
2140 * is " *", so from 1 to 2 we have a match and at position 2 we have
2141 * an empty match. */
2142 if (last_separator_end
!= match_info
->offsets
[1])
2147 token
= g_strndup (string
+ last_separator_end
,
2148 match_info
->offsets
[0] - last_separator_end
);
2149 list
= g_list_prepend (list
, token
);
2152 /* if there were substrings, these need to be added to
2154 match_count
= g_match_info_get_match_count (match_info
);
2155 if (match_count
> 1)
2157 for (i
= 1; i
< match_count
; i
++)
2158 list
= g_list_prepend (list
, g_match_info_fetch (match_info
, i
));
2164 /* if there was no match, copy to end of string. */
2165 if (!last_match_is_empty
)
2167 gchar
*token
= g_strndup (string
+ last_separator_end
,
2168 match_info
->string_len
- last_separator_end
);
2169 list
= g_list_prepend (list
, token
);
2171 /* no more tokens, end the loop. */
2175 /* -1 to leave room for the last part. */
2176 if (token_count
>= max_tokens
- 1)
2178 /* we have reached the maximum number of tokens, so we copy
2179 * the remaining part of the string. */
2180 if (last_match_is_empty
)
2182 /* the last match was empty, so we have moved one char
2183 * after the real position to avoid empty matches at the
2185 match_info
->pos
= PREV_CHAR (regex
, &string
[match_info
->pos
]) - string
;
2187 /* the if is needed in the case we have terminated the available
2188 * tokens, but we are at the end of the string, so there are no
2189 * characters left to copy. */
2190 if (string_len
> match_info
->pos
)
2192 gchar
*token
= g_strndup (string
+ match_info
->pos
,
2193 string_len
- match_info
->pos
);
2194 list
= g_list_prepend (list
, token
);
2200 last_separator_end
= match_info
->pos
;
2201 if (last_match_is_empty
)
2202 /* if the last match was empty, g_match_info_next() has moved
2203 * forward to avoid infinite loops, but we still need to copy that
2205 last_separator_end
= PREV_CHAR (regex
, &string
[last_separator_end
]) - string
;
2207 match_ok
= g_match_info_next (match_info
, &tmp_error
);
2209 g_match_info_free (match_info
);
2210 if (tmp_error
!= NULL
)
2212 g_propagate_error (error
, tmp_error
);
2213 g_list_free_full (list
, g_free
);
2214 match_info
->pos
= -1;
2218 string_list
= g_new (gchar
*, g_list_length (list
) + 1);
2220 for (last
= g_list_last (list
); last
; last
= g_list_previous (last
))
2221 string_list
[i
++] = last
->data
;
2222 string_list
[i
] = NULL
;
2231 REPL_TYPE_CHARACTER
,
2232 REPL_TYPE_SYMBOLIC_REFERENCE
,
2233 REPL_TYPE_NUMERIC_REFERENCE
,
2234 REPL_TYPE_CHANGE_CASE
2239 CHANGE_CASE_NONE
= 1 << 0,
2240 CHANGE_CASE_UPPER
= 1 << 1,
2241 CHANGE_CASE_LOWER
= 1 << 2,
2242 CHANGE_CASE_UPPER_SINGLE
= 1 << 3,
2243 CHANGE_CASE_LOWER_SINGLE
= 1 << 4,
2244 CHANGE_CASE_SINGLE_MASK
= CHANGE_CASE_UPPER_SINGLE
| CHANGE_CASE_LOWER_SINGLE
,
2245 CHANGE_CASE_LOWER_MASK
= CHANGE_CASE_LOWER
| CHANGE_CASE_LOWER_SINGLE
,
2246 CHANGE_CASE_UPPER_MASK
= CHANGE_CASE_UPPER
| CHANGE_CASE_UPPER_SINGLE
2249 struct _InterpolationData
2255 ChangeCase change_case
;
2259 free_interpolation_data (InterpolationData
*data
)
2261 g_free (data
->text
);
2265 static const gchar
*
2266 expand_escape (const gchar
*replacement
,
2268 InterpolationData
*data
,
2273 const gchar
*error_detail
;
2275 GError
*tmp_error
= NULL
;
2283 data
->type
= REPL_TYPE_CHARACTER
;
2288 data
->type
= REPL_TYPE_CHARACTER
;
2293 data
->type
= REPL_TYPE_CHARACTER
;
2298 data
->type
= REPL_TYPE_CHARACTER
;
2303 data
->type
= REPL_TYPE_CHARACTER
;
2308 data
->type
= REPL_TYPE_CHARACTER
;
2313 data
->type
= REPL_TYPE_CHARACTER
;
2318 data
->type
= REPL_TYPE_CHARACTER
;
2328 h
= g_ascii_xdigit_value (*p
);
2331 error_detail
= _("hexadecimal digit or '}' expected");
2342 for (i
= 0; i
< 2; i
++)
2344 h
= g_ascii_xdigit_value (*p
);
2347 error_detail
= _("hexadecimal digit expected");
2354 data
->type
= REPL_TYPE_STRING
;
2355 data
->text
= g_new0 (gchar
, 8);
2356 g_unichar_to_utf8 (x
, data
->text
);
2360 data
->type
= REPL_TYPE_CHANGE_CASE
;
2361 data
->change_case
= CHANGE_CASE_LOWER_SINGLE
;
2365 data
->type
= REPL_TYPE_CHANGE_CASE
;
2366 data
->change_case
= CHANGE_CASE_UPPER_SINGLE
;
2370 data
->type
= REPL_TYPE_CHANGE_CASE
;
2371 data
->change_case
= CHANGE_CASE_LOWER
;
2375 data
->type
= REPL_TYPE_CHANGE_CASE
;
2376 data
->change_case
= CHANGE_CASE_UPPER
;
2380 data
->type
= REPL_TYPE_CHANGE_CASE
;
2381 data
->change_case
= CHANGE_CASE_NONE
;
2387 error_detail
= _("missing '<' in symbolic reference");
2396 error_detail
= _("unfinished symbolic reference");
2403 error_detail
= _("zero-length symbolic reference");
2406 if (g_ascii_isdigit (*q
))
2411 h
= g_ascii_digit_value (*q
);
2414 error_detail
= _("digit expected");
2423 data
->type
= REPL_TYPE_NUMERIC_REFERENCE
;
2430 if (!g_ascii_isalnum (*r
))
2432 error_detail
= _("illegal symbolic reference");
2439 data
->text
= g_strndup (q
, p
- q
);
2440 data
->type
= REPL_TYPE_SYMBOLIC_REFERENCE
;
2445 /* if \0 is followed by a number is an octal number representing a
2446 * character, else it is a numeric reference. */
2447 if (g_ascii_digit_value (*g_utf8_next_char (p
)) >= 0)
2450 p
= g_utf8_next_char (p
);
2463 for (i
= 0; i
< 3; i
++)
2465 h
= g_ascii_digit_value (*p
);
2475 if (i
== 2 && base
== 10)
2481 if (base
== 8 || i
== 3)
2483 data
->type
= REPL_TYPE_STRING
;
2484 data
->text
= g_new0 (gchar
, 8);
2485 g_unichar_to_utf8 (x
, data
->text
);
2489 data
->type
= REPL_TYPE_NUMERIC_REFERENCE
;
2494 error_detail
= _("stray final '\\'");
2498 error_detail
= _("unknown escape sequence");
2505 /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
2506 tmp_error
= g_error_new (G_REGEX_ERROR
,
2507 G_REGEX_ERROR_REPLACE
,
2508 _("Error while parsing replacement "
2509 "text \"%s\" at char %lu: %s"),
2511 (gulong
)(p
- replacement
),
2513 g_propagate_error (error
, tmp_error
);
2519 split_replacement (const gchar
*replacement
,
2523 InterpolationData
*data
;
2524 const gchar
*p
, *start
;
2526 start
= p
= replacement
;
2531 data
= g_new0 (InterpolationData
, 1);
2532 start
= p
= expand_escape (replacement
, p
, data
, error
);
2535 g_list_free_full (list
, (GDestroyNotify
) free_interpolation_data
);
2536 free_interpolation_data (data
);
2540 list
= g_list_prepend (list
, data
);
2545 if (*p
== '\\' || *p
== '\0')
2549 data
= g_new0 (InterpolationData
, 1);
2550 data
->text
= g_strndup (start
, p
- start
);
2551 data
->type
= REPL_TYPE_STRING
;
2552 list
= g_list_prepend (list
, data
);
2558 return g_list_reverse (list
);
2561 /* Change the case of c based on change_case. */
2562 #define CHANGE_CASE(c, change_case) \
2563 (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
2564 g_unichar_tolower (c) : \
2565 g_unichar_toupper (c))
2568 string_append (GString
*string
,
2570 ChangeCase
*change_case
)
2574 if (text
[0] == '\0')
2577 if (*change_case
== CHANGE_CASE_NONE
)
2579 g_string_append (string
, text
);
2581 else if (*change_case
& CHANGE_CASE_SINGLE_MASK
)
2583 c
= g_utf8_get_char (text
);
2584 g_string_append_unichar (string
, CHANGE_CASE (c
, *change_case
));
2585 g_string_append (string
, g_utf8_next_char (text
));
2586 *change_case
= CHANGE_CASE_NONE
;
2590 while (*text
!= '\0')
2592 c
= g_utf8_get_char (text
);
2593 g_string_append_unichar (string
, CHANGE_CASE (c
, *change_case
));
2594 text
= g_utf8_next_char (text
);
2600 interpolate_replacement (const GMatchInfo
*match_info
,
2605 InterpolationData
*idata
;
2607 ChangeCase change_case
= CHANGE_CASE_NONE
;
2609 for (list
= data
; list
; list
= list
->next
)
2612 switch (idata
->type
)
2614 case REPL_TYPE_STRING
:
2615 string_append (result
, idata
->text
, &change_case
);
2617 case REPL_TYPE_CHARACTER
:
2618 g_string_append_c (result
, CHANGE_CASE (idata
->c
, change_case
));
2619 if (change_case
& CHANGE_CASE_SINGLE_MASK
)
2620 change_case
= CHANGE_CASE_NONE
;
2622 case REPL_TYPE_NUMERIC_REFERENCE
:
2623 match
= g_match_info_fetch (match_info
, idata
->num
);
2626 string_append (result
, match
, &change_case
);
2630 case REPL_TYPE_SYMBOLIC_REFERENCE
:
2631 match
= g_match_info_fetch_named (match_info
, idata
->text
);
2634 string_append (result
, match
, &change_case
);
2638 case REPL_TYPE_CHANGE_CASE
:
2639 change_case
= idata
->change_case
;
2647 /* whether actual match_info is needed for replacement, i.e.
2648 * whether there are references
2651 interpolation_list_needs_match (GList
*list
)
2653 while (list
!= NULL
)
2655 InterpolationData
*data
= list
->data
;
2657 if (data
->type
== REPL_TYPE_SYMBOLIC_REFERENCE
||
2658 data
->type
== REPL_TYPE_NUMERIC_REFERENCE
)
2671 * @regex: a #GRegex structure
2672 * @string: (array length=string_len): the string to perform matches against
2673 * @string_len: the length of @string, or -1 if @string is nul-terminated
2674 * @start_position: starting index of the string to match
2675 * @replacement: text to replace each match with
2676 * @match_options: options for the match
2677 * @error: location to store the error occurring, or %NULL to ignore errors
2679 * Replaces all occurrences of the pattern in @regex with the
2680 * replacement text. Backreferences of the form '\number' or
2681 * '\g<number>' in the replacement text are interpolated by the
2682 * number-th captured subexpression of the match, '\g<name>' refers
2683 * to the captured subexpression with the given name. '\0' refers to the
2684 * complete match, but '\0' followed by a number is the octal representation
2685 * of a character. To include a literal '\' in the replacement, write '\\'.
2686 * There are also escapes that changes the case of the following text:
2689 * <varlistentry><term>\l</term>
2691 * <para>Convert to lower case the next character</para>
2694 * <varlistentry><term>\u</term>
2696 * <para>Convert to upper case the next character</para>
2699 * <varlistentry><term>\L</term>
2701 * <para>Convert to lower case till \E</para>
2704 * <varlistentry><term>\U</term>
2706 * <para>Convert to upper case till \E</para>
2709 * <varlistentry><term>\E</term>
2711 * <para>End case modification</para>
2716 * If you do not need to use backreferences use g_regex_replace_literal().
2718 * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
2719 * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
2720 * you can use g_regex_replace_literal().
2722 * Setting @start_position differs from just passing over a shortened
2723 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
2724 * begins with any kind of lookbehind assertion, such as "\b".
2726 * Returns: a newly allocated string containing the replacements
2731 g_regex_replace (const GRegex
*regex
,
2732 const gchar
*string
,
2734 gint start_position
,
2735 const gchar
*replacement
,
2736 GRegexMatchFlags match_options
,
2741 GError
*tmp_error
= NULL
;
2743 g_return_val_if_fail (regex
!= NULL
, NULL
);
2744 g_return_val_if_fail (string
!= NULL
, NULL
);
2745 g_return_val_if_fail (start_position
>= 0, NULL
);
2746 g_return_val_if_fail (replacement
!= NULL
, NULL
);
2747 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
2748 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, NULL
);
2750 list
= split_replacement (replacement
, &tmp_error
);
2751 if (tmp_error
!= NULL
)
2753 g_propagate_error (error
, tmp_error
);
2757 result
= g_regex_replace_eval (regex
,
2758 string
, string_len
, start_position
,
2760 interpolate_replacement
,
2763 if (tmp_error
!= NULL
)
2764 g_propagate_error (error
, tmp_error
);
2766 g_list_free_full (list
, (GDestroyNotify
) free_interpolation_data
);
2772 literal_replacement (const GMatchInfo
*match_info
,
2776 g_string_append (result
, data
);
2781 * g_regex_replace_literal:
2782 * @regex: a #GRegex structure
2783 * @string: (array length=string_len): the string to perform matches against
2784 * @string_len: the length of @string, or -1 if @string is nul-terminated
2785 * @start_position: starting index of the string to match
2786 * @replacement: text to replace each match with
2787 * @match_options: options for the match
2788 * @error: location to store the error occurring, or %NULL to ignore errors
2790 * Replaces all occurrences of the pattern in @regex with the
2791 * replacement text. @replacement is replaced literally, to
2792 * include backreferences use g_regex_replace().
2794 * Setting @start_position differs from just passing over a
2795 * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
2796 * case of a pattern that begins with any kind of lookbehind
2797 * assertion, such as "\b".
2799 * Returns: a newly allocated string containing the replacements
2804 g_regex_replace_literal (const GRegex
*regex
,
2805 const gchar
*string
,
2807 gint start_position
,
2808 const gchar
*replacement
,
2809 GRegexMatchFlags match_options
,
2812 g_return_val_if_fail (replacement
!= NULL
, NULL
);
2813 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, NULL
);
2815 return g_regex_replace_eval (regex
,
2816 string
, string_len
, start_position
,
2818 literal_replacement
,
2819 (gpointer
)replacement
,
2824 * g_regex_replace_eval:
2825 * @regex: a #GRegex structure from g_regex_new()
2826 * @string: (array length=string_len): string to perform matches against
2827 * @string_len: the length of @string, or -1 if @string is nul-terminated
2828 * @start_position: starting index of the string to match
2829 * @match_options: options for the match
2830 * @eval: a function to call for each match
2831 * @user_data: user data to pass to the function
2832 * @error: location to store the error occurring, or %NULL to ignore errors
2834 * Replaces occurrences of the pattern in regex with the output of
2835 * @eval for that occurrence.
2837 * Setting @start_position differs from just passing over a shortened
2838 * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
2839 * that begins with any kind of lookbehind assertion, such as "\b".
2841 * The following example uses g_regex_replace_eval() to replace multiple
2845 * eval_cb (const GMatchInfo *info,
2852 * match = g_match_info_fetch (info, 0);
2853 * r = g_hash_table_lookup ((GHashTable *)data, match);
2854 * g_string_append (res, r);
2866 * h = g_hash_table_new (g_str_hash, g_str_equal);
2868 * g_hash_table_insert (h, "1", "ONE");
2869 * g_hash_table_insert (h, "2", "TWO");
2870 * g_hash_table_insert (h, "3", "THREE");
2871 * g_hash_table_insert (h, "4", "FOUR");
2873 * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
2874 * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
2875 * g_hash_table_destroy (h);
2880 * Returns: a newly allocated string containing the replacements
2885 g_regex_replace_eval (const GRegex
*regex
,
2886 const gchar
*string
,
2888 gint start_position
,
2889 GRegexMatchFlags match_options
,
2890 GRegexEvalCallback eval
,
2894 GMatchInfo
*match_info
;
2897 gboolean done
= FALSE
;
2898 GError
*tmp_error
= NULL
;
2900 g_return_val_if_fail (regex
!= NULL
, NULL
);
2901 g_return_val_if_fail (string
!= NULL
, NULL
);
2902 g_return_val_if_fail (start_position
>= 0, NULL
);
2903 g_return_val_if_fail (eval
!= NULL
, NULL
);
2904 g_return_val_if_fail ((match_options
& ~G_REGEX_MATCH_MASK
) == 0, NULL
);
2907 string_len
= strlen (string
);
2909 result
= g_string_sized_new (string_len
);
2911 /* run down the string making matches. */
2912 g_regex_match_full (regex
, string
, string_len
, start_position
,
2913 match_options
, &match_info
, &tmp_error
);
2914 while (!done
&& g_match_info_matches (match_info
))
2916 g_string_append_len (result
,
2918 match_info
->offsets
[0] - str_pos
);
2919 done
= (*eval
) (match_info
, result
, user_data
);
2920 str_pos
= match_info
->offsets
[1];
2921 g_match_info_next (match_info
, &tmp_error
);
2923 g_match_info_free (match_info
);
2924 if (tmp_error
!= NULL
)
2926 g_propagate_error (error
, tmp_error
);
2927 g_string_free (result
, TRUE
);
2931 g_string_append_len (result
, string
+ str_pos
, string_len
- str_pos
);
2932 return g_string_free (result
, FALSE
);
2936 * g_regex_check_replacement:
2937 * @replacement: the replacement string
2938 * @has_references: (out) (allow-none): location to store information about
2939 * references in @replacement or %NULL
2940 * @error: location to store error
2942 * Checks whether @replacement is a valid replacement string
2943 * (see g_regex_replace()), i.e. that all escape sequences in
2946 * If @has_references is not %NULL then @replacement is checked
2947 * for pattern references. For instance, replacement text 'foo\n'
2948 * does not contain references and may be evaluated without information
2949 * about actual match, but '\0\1' (whole match followed by first
2950 * subpattern) requires valid #GMatchInfo object.
2952 * Returns: whether @replacement is a valid replacement string
2957 g_regex_check_replacement (const gchar
*replacement
,
2958 gboolean
*has_references
,
2964 list
= split_replacement (replacement
, &tmp
);
2968 g_propagate_error (error
, tmp
);
2973 *has_references
= interpolation_list_needs_match (list
);
2975 g_list_free_full (list
, (GDestroyNotify
) free_interpolation_data
);
2981 * g_regex_escape_nul:
2982 * @string: the string to escape
2983 * @length: the length of @string
2985 * Escapes the nul characters in @string to "\x00". It can be used
2986 * to compile a regex with embedded nul characters.
2988 * For completeness, @length can be -1 for a nul-terminated string.
2989 * In this case the output string will be of course equal to @string.
2991 * Returns: a newly-allocated escaped string
2996 g_regex_escape_nul (const gchar
*string
,
3000 const gchar
*p
, *piece_start
, *end
;
3003 g_return_val_if_fail (string
!= NULL
, NULL
);
3006 return g_strdup (string
);
3008 end
= string
+ length
;
3009 p
= piece_start
= string
;
3010 escaped
= g_string_sized_new (length
+ 1);
3018 if (p
!= piece_start
)
3020 /* copy the previous piece. */
3021 g_string_append_len (escaped
, piece_start
, p
- piece_start
);
3023 if ((backslashes
& 1) == 0)
3024 g_string_append_c (escaped
, '\\');
3025 g_string_append_c (escaped
, 'x');
3026 g_string_append_c (escaped
, '0');
3027 g_string_append_c (escaped
, '0');
3037 p
= g_utf8_next_char (p
);
3042 if (piece_start
< end
)
3043 g_string_append_len (escaped
, piece_start
, end
- piece_start
);
3045 return g_string_free (escaped
, FALSE
);
3049 * g_regex_escape_string:
3050 * @string: (array length=length): the string to escape
3051 * @length: the length of @string, or -1 if @string is nul-terminated
3053 * Escapes the special characters used for regular expressions
3054 * in @string, for instance "a.b*c" becomes "a\.b\*c". This
3055 * function is useful to dynamically generate regular expressions.
3057 * @string can contain nul characters that are replaced with "\0",
3058 * in this case remember to specify the correct length of @string
3061 * Returns: a newly-allocated escaped string
3066 g_regex_escape_string (const gchar
*string
,
3070 const char *p
, *piece_start
, *end
;
3072 g_return_val_if_fail (string
!= NULL
, NULL
);
3075 length
= strlen (string
);
3077 end
= string
+ length
;
3078 p
= piece_start
= string
;
3079 escaped
= g_string_sized_new (length
+ 1);
3100 if (p
!= piece_start
)
3101 /* copy the previous piece. */
3102 g_string_append_len (escaped
, piece_start
, p
- piece_start
);
3103 g_string_append_c (escaped
, '\\');
3105 g_string_append_c (escaped
, '0');
3107 g_string_append_c (escaped
, *p
);
3111 p
= g_utf8_next_char (p
);
3116 if (piece_start
< end
)
3117 g_string_append_len (escaped
, piece_start
, end
- piece_start
);
3119 return g_string_free (escaped
, FALSE
);