Tizen 2.1 base
[platform/upstream/glib2.0.git] / docs / reference / glib / html / glib-regex-syntax.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
5 <title>Regular expression syntax</title>
6 <meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
7 <link rel="home" href="index.html" title="GLib Reference Manual">
8 <link rel="up" href="glib-utilities.html" title="GLib Utilities">
9 <link rel="prev" href="glib-Perl-compatible-regular-expressions.html" title="Perl-compatible regular expressions">
10 <link rel="next" href="glib-Simple-XML-Subset-Parser.html" title="Simple XML Subset Parser">
11 <meta name="generator" content="GTK-Doc V1.18 (XML mode)">
12 <link rel="stylesheet" href="style.css" type="text/css">
13 </head>
14 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
15 <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2"><tr valign="middle">
16 <td><a accesskey="p" href="glib-Perl-compatible-regular-expressions.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
17 <td><a accesskey="u" href="glib-utilities.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td>
18 <td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
19 <th width="100%" align="center">GLib Reference Manual</th>
20 <td><a accesskey="n" href="glib-Simple-XML-Subset-Parser.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
21 </tr></table>
22 <div class="refentry">
23 <a name="glib-regex-syntax"></a><div class="titlepage"></div>
24 <div class="refnamediv"><table width="100%"><tr>
25 <td valign="top">
26 <h2><span class="refentrytitle">Regular expression syntax</span></h2>
27 <p>Regular expression syntax — 
28 syntax and semantics of regular expressions supported by GRegex
29 </p>
30 </td>
31 <td valign="top" align="right"></td>
32 </tr></table></div>
33 <div class="refsect1">
34 <a name="id644360"></a><h2>GRegex regular expression details</h2>
35 <p>
36 A regular expression is a pattern that is matched against a
37 string from left to right. Most characters stand for themselves in a
38 pattern, and match the corresponding characters in the string. As a
39 trivial example, the pattern
40 </p>
41 <pre class="programlisting">
42 The quick brown fox
43 </pre>
44 <p>
45 matches a portion of a string that is identical to itself. When
46 caseless matching is specified (the <code class="varname">G_REGEX_CASELESS</code> flag), letters are
47 matched independently of case.
48 </p>
49 <p>
50 The power of regular expressions comes from the ability to include
51 alternatives and repetitions in the pattern. These are encoded in the
52 pattern by the use of metacharacters, which do not stand for themselves
53 but instead are interpreted in some special way.
54 </p>
55 <p>
56 There are two different sets of metacharacters: those that are recognized
57 anywhere in the pattern except within square brackets, and those
58 that are recognized in square brackets. Outside square brackets, the
59 metacharacters are as follows:
60 </p>
61 <div class="table">
62 <a name="id474310"></a><p class="title"><b>Table 1. Metacharacters outside square brackets</b></p>
63 <div class="table-contents"><table summary="Metacharacters outside square brackets" border="1">
64 <colgroup>
65 <col align="center">
66 <col>
67 </colgroup>
68 <thead><tr>
69 <th align="center">Character</th>
70 <th>Meaning</th>
71 </tr></thead>
72 <tbody>
73 <tr>
74 <td align="center">\</td>
75 <td>general escape character with several uses</td>
76 </tr>
77 <tr>
78 <td align="center">^</td>
79 <td>assert start of string (or line, in multiline mode)</td>
80 </tr>
81 <tr>
82 <td align="center">$</td>
83 <td>assert end of string (or line, in multiline mode)</td>
84 </tr>
85 <tr>
86 <td align="center">.</td>
87 <td>match any character except newline (by default)</td>
88 </tr>
89 <tr>
90 <td align="center">[</td>
91 <td>start character class definition</td>
92 </tr>
93 <tr>
94 <td align="center">|</td>
95 <td>start of alternative branch</td>
96 </tr>
97 <tr>
98 <td align="center">(</td>
99 <td>start subpattern</td>
100 </tr>
101 <tr>
102 <td align="center">)</td>
103 <td>end subpattern</td>
104 </tr>
105 <tr>
106 <td align="center">?</td>
107 <td>extends the meaning of (, or 0/1 quantifier, or quantifier minimizer</td>
108 </tr>
109 <tr>
110 <td align="center">*</td>
111 <td>0 or more quantifier</td>
112 </tr>
113 <tr>
114 <td align="center">+</td>
115 <td>1 or more quantifier, also "possessive quantifier"</td>
116 </tr>
117 <tr>
118 <td align="center">{</td>
119 <td>start min/max quantifier</td>
120 </tr>
121 </tbody>
122 </table></div>
123 </div>
124 <br class="table-break"><p>
125 Part of a pattern that is in square brackets is called a "character
126 class". In a character class the only metacharacters are:
127 </p>
128 <div class="table">
129 <a name="id714158"></a><p class="title"><b>Table 2. Metacharacters inside square brackets</b></p>
130 <div class="table-contents"><table summary="Metacharacters inside square brackets" border="1">
131 <colgroup>
132 <col align="center">
133 <col>
134 </colgroup>
135 <thead><tr>
136 <th align="center">Character</th>
137 <th>Meaning</th>
138 </tr></thead>
139 <tbody>
140 <tr>
141 <td align="center">\</td>
142 <td>general escape character</td>
143 </tr>
144 <tr>
145 <td align="center">^</td>
146 <td>negate the class, but only if the first character</td>
147 </tr>
148 <tr>
149 <td align="center">-</td>
150 <td>indicates character range</td>
151 </tr>
152 <tr>
153 <td align="center">[</td>
154 <td>POSIX character class (only if followed by POSIX syntax)</td>
155 </tr>
156 <tr>
157 <td align="center">]</td>
158 <td>terminates the character class</td>
159 </tr>
160 </tbody>
161 </table></div>
162 </div>
163 <br class="table-break">
164 </div>
165 <div class="refsect1">
166 <a name="id723746"></a><h2>Backslash</h2>
167 <p>
168 The backslash character has several uses. Firstly, if it is followed by
169 a non-alphanumeric character, it takes away any special meaning that
170 character may have. This use of backslash as an escape character
171 applies both inside and outside character classes.
172 </p>
173 <p>
174 For example, if you want to match a * character, you write \* in the
175 pattern. This escaping action applies whether or not the following
176 character would otherwise be interpreted as a metacharacter, so it is
177 always safe to precede a non-alphanumeric with backslash to specify
178 that it stands for itself. In particular, if you want to match a
179 backslash, you write \\.
180 </p>
181 <p>
182 If a pattern is compiled with the <code class="varname">G_REGEX_EXTENDED</code>
183 option, whitespace in the pattern (other than in a character class) and
184 characters between a # outside a character class and the next newline
185 are ignored.
186 An escaping backslash can be used to include a whitespace or # character
187 as part of the pattern.
188 </p>
189 <p>
190 Note that the C compiler interprets backslash in strings itself, therefore
191 you need to duplicate all \ characters when you put a regular expression
192 in a C string, like "\\d{3}".
193 </p>
194 <p>
195 If you want to remove the special meaning from a sequence of characters,
196 you can do so by putting them between \Q and \E.
197 The \Q...\E sequence is recognized both inside and outside character
198 classes.
199 </p>
200 <div class="refsect2">
201 <a name="id723784"></a><h3>Non-printing characters</h3>
202 <p>
203 A second use of backslash provides a way of encoding non-printing
204 characters in patterns in a visible manner. There is no restriction on the
205 appearance of non-printing characters, apart from the binary zero that
206 terminates a pattern, but when a pattern is being prepared by text
207 editing, it is usually easier to use one of the following escape
208 sequences than the binary character it represents:
209 </p>
210 <div class="table">
211 <a name="id723797"></a><p class="title"><b>Table 3. Non-printing characters</b></p>
212 <div class="table-contents"><table summary="Non-printing characters" border="1">
213 <colgroup>
214 <col align="center">
215 <col>
216 </colgroup>
217 <thead><tr>
218 <th align="center">Escape</th>
219 <th>Meaning</th>
220 </tr></thead>
221 <tbody>
222 <tr>
223 <td align="center">\a</td>
224 <td>alarm, that is, the BEL character (hex 07)</td>
225 </tr>
226 <tr>
227 <td align="center">\cx</td>
228 <td>"control-x", where x is any character</td>
229 </tr>
230 <tr>
231 <td align="center">\e</td>
232 <td>escape (hex 1B)</td>
233 </tr>
234 <tr>
235 <td align="center">\f</td>
236 <td>formfeed (hex 0C)</td>
237 </tr>
238 <tr>
239 <td align="center">\n</td>
240 <td>newline (hex 0A)</td>
241 </tr>
242 <tr>
243 <td align="center">\r</td>
244 <td>carriage return (hex 0D)</td>
245 </tr>
246 <tr>
247 <td align="center">\t</td>
248 <td>tab (hex 09)</td>
249 </tr>
250 <tr>
251 <td align="center">\ddd</td>
252 <td>character with octal code ddd, or backreference</td>
253 </tr>
254 <tr>
255 <td align="center">\xhh</td>
256 <td>character with hex code hh</td>
257 </tr>
258 <tr>
259 <td align="center">\x{hhh..}</td>
260 <td>character with hex code hhh..</td>
261 </tr>
262 </tbody>
263 </table></div>
264 </div>
265 <br class="table-break"><p>
266 The precise effect of \cx is as follows: if x is a lower case letter,
267 it is converted to upper case. Then bit 6 of the character (hex 40) is
268 inverted. Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c;
269 becomes hex 7B.
270 </p>
271 <p>
272 After \x, from zero to two hexadecimal digits are read (letters can be
273 in upper or lower case). Any number of hexadecimal digits may appear
274 between \x{ and }, but the value of the character code
275 must be less than 2**31 (that is, the maximum hexadecimal value is
276 7FFFFFFF). If characters other than hexadecimal digits appear between
277 \x{ and }, or if there is no terminating }, this form of escape is not
278 recognized. Instead, the initial \x will be interpreted as a basic hexadecimal
279 escape, with no following digits, giving a character whose
280 value is zero.
281 </p>
282 <p>
283 Characters whose value is less than 256 can be defined by either of the
284 two syntaxes for \x. There is no difference
285 in the way they are handled. For example, \xdc is exactly the same as
286 \x{dc}.
287 </p>
288 <p>
289 After \0 up to two further octal digits are read. If there are fewer
290 than two digits, just those that are present are used.
291 Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL
292 character (code value 7). Make sure you supply two digits after the
293 initial zero if the pattern character that follows is itself an octal
294 digit.
295 </p>
296 <p>
297 The handling of a backslash followed by a digit other than 0 is complicated.
298 Outside a character class, GRegex reads it and any following digits as a
299 decimal number. If the number is less than 10, or if there
300 have been at least that many previous capturing left parentheses in the
301 expression, the entire sequence is taken as a back reference. A
302 description of how this works is given later, following the discussion
303 of parenthesized subpatterns.
304 </p>
305 <p>
306 Inside a character class, or if the decimal number is greater than 9
307 and there have not been that many capturing subpatterns, GRegex re-reads
308 up to three octal digits following the backslash, and uses them to generate
309 a data character. Any subsequent digits stand for themselves. For example:
310 </p>
311 <div class="table">
312 <a name="id721672"></a><p class="title"><b>Table 4. Non-printing characters</b></p>
313 <div class="table-contents"><table summary="Non-printing characters" border="1">
314 <colgroup>
315 <col align="center">
316 <col>
317 </colgroup>
318 <thead><tr>
319 <th align="center">Escape</th>
320 <th>Meaning</th>
321 </tr></thead>
322 <tbody>
323 <tr>
324 <td align="center">\040</td>
325 <td>is another way of writing a space</td>
326 </tr>
327 <tr>
328 <td align="center">\40</td>
329 <td>is the same, provided there are fewer than 40 previous capturing subpatterns</td>
330 </tr>
331 <tr>
332 <td align="center">\7</td>
333 <td>is always a back reference</td>
334 </tr>
335 <tr>
336 <td align="center">\11</td>
337 <td>might be a back reference, or another way of writing a tab</td>
338 </tr>
339 <tr>
340 <td align="center">\011</td>
341 <td>is always a tab</td>
342 </tr>
343 <tr>
344 <td align="center">\0113</td>
345 <td>is a tab followed by the character "3"</td>
346 </tr>
347 <tr>
348 <td align="center">\113</td>
349 <td>might be a back reference, otherwise the character with octal code 113</td>
350 </tr>
351 <tr>
352 <td align="center">\377</td>
353 <td>might be a back reference, otherwise the byte consisting entirely of 1 bits</td>
354 </tr>
355 <tr>
356 <td align="center">\81</td>
357 <td>is either a back reference, or a binary zero followed by the two characters "8" and "1"</td>
358 </tr>
359 </tbody>
360 </table></div>
361 </div>
362 <br class="table-break"><p>
363 Note that octal values of 100 or greater must not be introduced by a
364 leading zero, because no more than three octal digits are ever read.
365 </p>
366 <p>
367 All the sequences that define a single character can be used both inside
368 and outside character classes. In addition, inside a character class, the
369 sequence \b is interpreted as the backspace character (hex 08), and the
370 sequences \R and \X are interpreted as the characters "R" and "X", respectively.
371 Outside a character class, these sequences have different meanings (see below).
372 </p>
373 </div>
374 <hr>
375 <div class="refsect2">
376 <a name="id721830"></a><h3>Absolute and relative back references</h3>
377 <p>
378 The sequence \g followed by a positive or negative number, optionally enclosed
379 in braces, is an absolute or relative back reference. Back references are
380 discussed later, following the discussion of parenthesized subpatterns.
381 </p>
382 </div>
383 <hr>
384 <div class="refsect2">
385 <a name="id721844"></a><h3>Generic character types</h3>
386 <p>
387 Another use of backslash is for specifying generic character types.
388 The following are always recognized:
389 </p>
390 <div class="table">
391 <a name="id721854"></a><p class="title"><b>Table 5. Generic characters</b></p>
392 <div class="table-contents"><table summary="Generic characters" border="1">
393 <colgroup>
394 <col align="center">
395 <col>
396 </colgroup>
397 <thead><tr>
398 <th align="center">Escape</th>
399 <th>Meaning</th>
400 </tr></thead>
401 <tbody>
402 <tr>
403 <td align="center">\d</td>
404 <td>any decimal digit</td>
405 </tr>
406 <tr>
407 <td align="center">\D</td>
408 <td>any character that is not a decimal digit</td>
409 </tr>
410 <tr>
411 <td align="center">\s</td>
412 <td>any whitespace character</td>
413 </tr>
414 <tr>
415 <td align="center">\S</td>
416 <td>any character that is not a whitespace character</td>
417 </tr>
418 <tr>
419 <td align="center">\w</td>
420 <td>any "word" character</td>
421 </tr>
422 <tr>
423 <td align="center">\W</td>
424 <td>any "non-word" character</td>
425 </tr>
426 </tbody>
427 </table></div>
428 </div>
429 <br class="table-break"><p>
430 Each pair of escape sequences partitions the complete set of characters
431 into two disjoint sets. Any given character matches one, and only one,
432 of each pair.
433 </p>
434 <p>
435 These character type sequences can appear both inside and outside character
436 classes. They each match one character of the appropriate type.
437 If the current matching point is at the end of the passed string, all
438 of them fail, since there is no character to match.
439 </p>
440 <p>
441 For compatibility with Perl, \s does not match the VT character (code
442 11). This makes it different from the the POSIX "space" class. The \s
443 characters are HT (9), LF (10), FF (12), CR (13), and space (32).
444 </p>
445 <p>
446 A "word" character is an underscore or any character less than 256 that
447 is a letter or digit.</p>
448 <p>
449 Characters with values greater than 128 never match \d,
450 \s, or \w, and always match \D, \S, and \W.
451 </p>
452 </div>
453 <hr>
454 <div class="refsect2">
455 <a name="id721993"></a><h3>Newline sequences</h3>
456 <p>Outside a character class, the escape sequence \R matches any Unicode
457 newline sequence.
458 This particular group matches either the two-character sequence CR followed by
459 LF, or one of the single characters LF (linefeed, U+000A), VT (vertical tab,
460 U+000B), FF (formfeed, U+000C), CR (carriage return, U+000D), NEL (next
461 line, U+0085), LS (line separator, U+2028), or PS (paragraph separator, U+2029).
462 The two-character sequence is treated as a single unit that
463 cannot be split. Inside a character class, \R matches the letter "R".</p>
464 </div>
465 <hr>
466 <div class="refsect2">
467 <a name="id722009"></a><h3>Unicode character properties</h3>
468 <p>
469 To support generic character types there are three additional escape
470 sequences, they are:
471 </p>
472 <div class="table">
473 <a name="id722019"></a><p class="title"><b>Table 6. Generic character types</b></p>
474 <div class="table-contents"><table summary="Generic character types" border="1">
475 <colgroup>
476 <col align="center">
477 <col>
478 </colgroup>
479 <thead><tr>
480 <th align="center">Escape</th>
481 <th>Meaning</th>
482 </tr></thead>
483 <tbody>
484 <tr>
485 <td align="center">\p{xx}</td>
486 <td>a character with the xx property</td>
487 </tr>
488 <tr>
489 <td align="center">\P{xx}</td>
490 <td>a character without the xx property</td>
491 </tr>
492 <tr>
493 <td align="center">\X</td>
494 <td>an extended Unicode sequence</td>
495 </tr>
496 </tbody>
497 </table></div>
498 </div>
499 <br class="table-break"><p>
500 The property names represented by xx above are limited to the Unicode
501 script names, the general category properties, and "Any", which matches
502 any character (including newline). Other properties such as "InMusicalSymbols"
503 are not currently supported. Note that \P{Any} does not match any characters,
504 so always causes a match failure.
505 </p>
506 <p>
507 Sets of Unicode characters are defined as belonging to certain scripts. A
508 character from one of these sets can be matched using a script name. For
509 example, \p{Greek} or \P{Han}.
510 </p>
511 <p>
512 Those that are not part of an identified script are lumped together as
513 "Common". The current list of scripts can be found in the documentation for
514 the #GUnicodeScript enumeration. Script names for use with \p{} can be
515 found by replacing all spaces with underscores, e.g. for Linear B use
516 \p{Linear_B}.
517 </p>
518 <p>
519 Each character has exactly one general category property, specified by a
520 two-letter abbreviation. For compatibility with Perl, negation can be specified
521 by including a circumflex between the opening brace and the property name. For
522 example, \p{^Lu} is the same as \P{Lu}.
523 </p>
524 <p>
525 If only one letter is specified with \p or \P, it includes all the general
526 category properties that start with that letter. In this case, in the absence
527 of negation, the curly brackets in the escape sequence are optional; these two
528 examples have the same effect:
529 </p>
530 <pre class="programlisting">
531 \p{L}
532 \pL
533 </pre>
534 <p>
535 In addition to the two-letter category codes listed in the
536 documentation for the #GUnicodeType enumeration, the following
537 general category property codes are supported:
538 </p>
539 <div class="table">
540 <a name="id722140"></a><p class="title"><b>Table 7. Property codes</b></p>
541 <div class="table-contents"><table summary="Property codes" border="1">
542 <colgroup>
543 <col align="center">
544 <col>
545 </colgroup>
546 <thead><tr>
547 <th align="center">Code</th>
548 <th>Meaning</th>
549 </tr></thead>
550 <tbody>
551 <tr>
552 <td align="center">C</td>
553 <td>Other</td>
554 </tr>
555 <tr>
556 <td align="center">L</td>
557 <td>Letter</td>
558 </tr>
559 <tr>
560 <td align="center">M</td>
561 <td>Mark</td>
562 </tr>
563 <tr>
564 <td align="center">N</td>
565 <td>Number</td>
566 </tr>
567 <tr>
568 <td align="center">P</td>
569 <td>Punctuation</td>
570 </tr>
571 <tr>
572 <td align="center">S</td>
573 <td>Symbol</td>
574 </tr>
575 <tr>
576 <td align="center">Z</td>
577 <td>Separator</td>
578 </tr>
579 </tbody>
580 </table></div>
581 </div>
582 <br class="table-break"><p>
583 The special property L&amp; is also supported: it matches a character that has
584 the Lu, Ll, or Lt property, in other words, a letter that is not classified as
585 a modifier or "other".
586 </p>
587 <p>
588 The long synonyms for these properties that Perl supports (such as \ep{Letter})
589 are not supported by GRegex, nor is it permitted to prefix any of these
590 properties with "Is".
591 </p>
592 <p>
593 No character that is in the Unicode table has the Cn (unassigned) property.
594 Instead, this property is assumed for any code point that is not in the
595 Unicode table.
596 </p>
597 <p>
598 Specifying caseless matching does not affect these escape sequences.
599 For example, \p{Lu} always matches only upper case letters.
600 </p>
601 <p>
602 The \X escape matches any number of Unicode characters that form an
603 extended Unicode sequence. \X is equivalent to
604 </p>
605 <pre class="programlisting">
606 (?&gt;\PM\pM*)
607 </pre>
608 <p>
609 That is, it matches a character without the "mark" property, followed
610 by zero or more characters with the "mark" property, and treats the
611 sequence as an atomic group (see below). Characters with the "mark"
612 property are typically accents that affect the preceding character.
613 </p>
614 <p>
615 Matching characters by Unicode property is not fast, because GRegex has
616 to search a structure that contains data for over fifteen thousand
617 characters. That is why the traditional escape sequences such as \d and
618 \w do not use Unicode properties.
619 </p>
620 </div>
621 <hr>
622 <div class="refsect2">
623 <a name="id722307"></a><h3>Simple assertions</h3>
624 <p>
625 The final use of backslash is for certain simple assertions. An
626 assertion specifies a condition that has to be met at a particular point in
627 a match, without consuming any characters from the string. The
628 use of subpatterns for more complicated assertions is described below.
629 The backslashed assertions are:
630 </p>
631 <div class="table">
632 <a name="id722319"></a><p class="title"><b>Table 8. Simple assertions</b></p>
633 <div class="table-contents"><table summary="Simple assertions" border="1">
634 <colgroup>
635 <col align="center">
636 <col>
637 </colgroup>
638 <thead><tr>
639 <th align="center">Escape</th>
640 <th>Meaning</th>
641 </tr></thead>
642 <tbody>
643 <tr>
644 <td align="center">\b</td>
645 <td>matches at a word boundary</td>
646 </tr>
647 <tr>
648 <td align="center">\B</td>
649 <td>matches when not at a word boundary</td>
650 </tr>
651 <tr>
652 <td align="center">\A</td>
653 <td>matches at the start of the string</td>
654 </tr>
655 <tr>
656 <td align="center">\Z</td>
657 <td>matches at the end of the string or before a newline at the end of the string</td>
658 </tr>
659 <tr>
660 <td align="center">\z</td>
661 <td>matches only at the end of the string</td>
662 </tr>
663 <tr>
664 <td align="center">\G</td>
665 <td>matches at first matching position in the string</td>
666 </tr>
667 </tbody>
668 </table></div>
669 </div>
670 <br class="table-break"><p>
671 These assertions may not appear in character classes (but note that \b
672 has a different meaning, namely the backspace character, inside a
673 character class).
674 </p>
675 <p>
676 A word boundary is a position in the string where the current
677 character and the previous character do not both match \w or \W (i.e.
678 one matches \w and the other matches \W), or the start or end of the
679 string if the first or last character matches \w, respectively.
680 </p>
681 <p>
682 The \A, \Z, and \z assertions differ from the traditional circumflex
683 and dollar (described in the next section) in that they only ever match
684 at the very start and end of the string, whatever options are
685 set. Thus, they are independent of multiline mode. These three assertions
686 are not affected by the <code class="varname">G_REGEX_MATCH_NOTBOL</code> or <code class="varname">G_REGEX_MATCH_NOTEOL</code> options,
687 which affect only the behaviour of the circumflex and dollar metacharacters.
688 However, if the start_position argument of a matching function is non-zero,
689 indicating that matching is to start at a point other than the beginning of
690 the string, \A can never match. The difference between \Z and \z is
691 that \Z matches before a newline at the end of the string as well at the
692 very end, whereas \z matches only at the end.
693 </p>
694 <p>
695 The \G assertion is true only when the current matching position is at
696 the start point of the match, as specified by the start_position argument
697 to the matching functions. It differs from \A when the value of startoffset is
698 non-zero.
699 </p>
700 <p>
701 Note, however, that the interpretation of \G, as the start of the
702 current match, is subtly different from Perl’s, which defines it as the
703 end of the previous match. In Perl, these can be different when the
704 previously matched string was empty.
705 </p>
706 <p>
707 If all the alternatives of a pattern begin with \G, the expression is
708 anchored to the starting match position, and the "anchored" flag is set
709 in the compiled regular expression.
710 </p>
711 </div>
712 </div>
713 <div class="refsect1">
714 <a name="id722479"></a><h2>Circumflex and dollar</h2>
715 <p>
716 Outside a character class, in the default matching mode, the circumflex
717 character is an assertion that is true only if the current matching
718 point is at the start of the string. If the start_position argument to
719 the matching functions is non-zero, circumflex can never match if the
720 <code class="varname">G_REGEX_MULTILINE</code> option is unset. Inside a character class, circumflex
721 has an entirely different meaning (see below).
722 </p>
723 <p>
724 Circumflex need not be the first character of the pattern if a number
725 of alternatives are involved, but it should be the first thing in each
726 alternative in which it appears if the pattern is ever to match that
727 branch. If all possible alternatives start with a circumflex, that is,
728 if the pattern is constrained to match only at the start of the string,
729 it is said to be an "anchored" pattern. (There are also other
730 constructs that can cause a pattern to be anchored.)
731 </p>
732 <p>
733 A dollar character is an assertion that is true only if the current
734 matching point is at the end of the string, or immediately
735 before a newline at the end of the string (by default). Dollar need not
736 be the last character of the pattern if a number of alternatives are
737 involved, but it should be the last item in any branch in which it
738 appears. Dollar has no special meaning in a character class.
739 </p>
740 <p>
741 The meaning of dollar can be changed so that it matches only at the
742 very end of the string, by setting the <code class="varname">G_REGEX_DOLLAR_ENDONLY</code> option at
743 compile time. This does not affect the \Z assertion.
744 </p>
745 <p>
746 The meanings of the circumflex and dollar characters are changed if the
747 <code class="varname">G_REGEX_MULTILINE</code> option is set. When this is the case,
748 a circumflex matches immediately after internal newlines as well as at the
749 start of the string. It does not match after a newline that ends the string.
750 A dollar matches before any newlines in the string, as well as at the very
751 end, when <code class="varname">G_REGEX_MULTILINE</code> is set. When newline is
752 specified as the two-character sequence CRLF, isolated CR and LF characters
753 do not indicate newlines.
754 </p>
755 <p>
756 For example, the pattern /^abc$/ matches the string "def\nabc" (where
757 \n represents a newline) in multiline mode, but not otherwise. Consequently,
758 patterns that are anchored in single line mode because all branches start with
759 ^ are not anchored in multiline mode, and a match for circumflex is possible
760 when the <code class="varname">start_position</code> argument of a matching function
761 is non-zero. The <code class="varname">G_REGEX_DOLLAR_ENDONLY</code> option is ignored
762 if <code class="varname">G_REGEX_MULTILINE</code> is set.
763 </p>
764 <p>
765 Note that the sequences \A, \Z, and \z can be used to match the start and
766 end of the string in both modes, and if all branches of a pattern start with
767 \A it is always anchored, whether or not <code class="varname">G_REGEX_MULTILINE</code>
768 is set.
769 </p>
770 </div>
771 <div class="refsect1">
772 <a name="id722559"></a><h2>Full stop (period, dot)</h2>
773 <p>
774 Outside a character class, a dot in the pattern matches any one character
775 in the string, including a non-printing character, but not (by
776 default) newline. In UTF-8 a character might be more than one byte long.
777 </p>
778 <p>
779 When a line ending is defined as a single character, dot never matches that
780 character; when the two-character sequence CRLF is used, dot does not match CR
781 if it is immediately followed by LF, but otherwise it matches all characters
782 (including isolated CRs and LFs). When any Unicode line endings are being
783 recognized, dot does not match CR or LF or any of the other line ending
784 characters.
785 </p>
786 <p>
787 If the <code class="varname">G_REGEX_DOTALL</code> flag is set, dots match newlines
788 as well. The handling of dot is entirely independent of the handling of circumflex
789 and dollar, the only relationship being that they both involve newline
790 characters. Dot has no special meaning in a character class.
791 </p>
792 <p>
793 The behaviour of dot with regard to newlines can be changed. If the
794 <code class="varname">G_REGEX_DOTALL</code> option is set, a dot matches any one
795 character, without exception. If newline is defined as the two-character
796 sequence CRLF, it takes two dots to match it.
797 </p>
798 <p>
799 The handling of dot is entirely independent of the handling of circumflex and
800 dollar, the only relationship being that they both involve newlines. Dot has no
801 special meaning in a character class.
802 </p>
803 </div>
804 <div class="refsect1">
805 <a name="id722602"></a><h2>Matching a single byte</h2>
806 <p>
807 Outside a character class, the escape sequence \C matches any one byte,
808 both in and out of UTF-8 mode. Unlike a dot, it always matches any line
809 ending characters.
810 The feature is provided in Perl in order to match individual bytes in
811 UTF-8 mode. Because it breaks up UTF-8 characters into individual
812 bytes, what remains in the string may be a malformed UTF-8 string. For
813 this reason, the \C escape sequence is best avoided.
814 </p>
815 <p>
816 GRegex does not allow \C to appear in lookbehind assertions (described
817 below), because in UTF-8 mode this would make it impossible to calculate
818 the length of the lookbehind.
819 </p>
820 </div>
821 <div class="refsect1">
822 <a name="id722622"></a><h2>Square brackets and character classes</h2>
823 <p>
824 An opening square bracket introduces a character class, terminated by a
825 closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class,
826 it should be the first data character in the class (after an initial
827 circumflex, if present) or escaped with a backslash.
828 </p>
829 <p>
830 A character class matches a single character in the string.  A matched character
831 must be in the set of characters defined by the class, unless the first
832 character in the class definition is a circumflex, in which case the
833 string character must not be in the set defined by the class. If a
834 circumflex is actually required as a member of the class, ensure it is
835 not the first character, or escape it with a backslash.
836 </p>
837 <p>
838 For example, the character class [aeiou] matches any lower case vowel,
839 while [^aeiou] matches any character that is not a lower case vowel.
840 Note that a circumflex is just a convenient notation for specifying the
841 characters that are in the class by enumerating those that are not. A
842 class that starts with a circumflex is not an assertion: it still consumes
843 a character from the string, and therefore it fails if the current pointer
844 is at the end of the string.
845 </p>
846 <p>
847 In UTF-8 mode, characters with values greater than 255 can be included
848 in a class as a literal string of bytes, or by using the \x{ escaping
849 mechanism.
850 </p>
851 <p>
852 When caseless matching is set, any letters in a class represent both
853 their upper case and lower case versions, so for example, a caseless
854 [aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not
855 match "A", whereas a caseful version would.
856 </p>
857 <p>
858 Characters that might indicate line breaks are never treated
859 in any special way when matching character classes, whatever line-ending
860 sequence is in use, and whatever setting of the <code class="varname">G_REGEX_DOTALL</code>
861 and <code class="varname">G_REGEX_MULTILINE</code> options is used. A class such as [^a]
862 always matches one of these characters.
863 </p>
864 <p>
865 The minus (hyphen) character can be used to specify a range of characters in
866 a character class. For example, [d-m] matches any letter
867 between d and m, inclusive. If a minus character is required in a
868 class, it must be escaped with a backslash or appear in a position
869 where it cannot be interpreted as indicating a range, typically as the
870 first or last character in the class.
871 </p>
872 <p>
873 It is not possible to have the literal character "]" as the end character
874 of a range. A pattern such as [W-]46] is interpreted as a class of
875 two characters ("W" and "-") followed by a literal string "46]", so it
876 would match "W46]" or "-46]". However, if the "]" is escaped with a
877 backslash it is interpreted as the end of range, so [W-\]46] is interpreted
878 as a class containing a range followed by two other characters.
879 The octal or hexadecimal representation of "]" can also be used to end
880 a range.
881 </p>
882 <p>
883 Ranges operate in the collating sequence of character values. They can
884 also be used for characters specified numerically, for example
885 [\000-\037]. In UTF-8 mode, ranges can include characters whose values
886 are greater than 255, for example [\x{100}-\x{2ff}].
887 </p>
888 <p>
889 The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear
890 in a character class, and add the characters that they match to the
891 class. For example, [\dABCDEF] matches any hexadecimal digit. A
892 circumflex can conveniently be used with the upper case character types to
893 specify a more restricted set of characters than the matching lower
894 case type. For example, the class [^\W_] matches any letter or digit,
895 but not underscore.
896 </p>
897 <p>
898 The only metacharacters that are recognized in character classes are
899 backslash, hyphen (only where it can be interpreted as specifying a
900 range), circumflex (only at the start), opening square bracket (only
901 when it can be interpreted as introducing a POSIX class name - see the
902 next section), and the terminating closing square bracket. However,
903 escaping other non-alphanumeric characters does no harm.
904 </p>
905 </div>
906 <div class="refsect1">
907 <a name="id722708"></a><h2>Posix character classes</h2>
908 <p>
909 GRegex supports the POSIX notation for character classes. This uses names
910 enclosed by [: and :] within the enclosing square brackets. For example,
911 </p>
912 <pre class="programlisting">
913 [01[:alpha:]%]
914 </pre>
915 <p>
916 matches "0", "1", any alphabetic character, or "%". The supported class
917 names are
918 </p>
919 <div class="table">
920 <a name="id722728"></a><p class="title"><b>Table 9. Posix classes</b></p>
921 <div class="table-contents"><table summary="Posix classes" border="1">
922 <colgroup>
923 <col align="center">
924 <col>
925 </colgroup>
926 <thead><tr>
927 <th align="center">Name</th>
928 <th>Meaning</th>
929 </tr></thead>
930 <tbody>
931 <tr>
932 <td align="center">alnum</td>
933 <td>letters and digits</td>
934 </tr>
935 <tr>
936 <td align="center">alpha</td>
937 <td>letters</td>
938 </tr>
939 <tr>
940 <td align="center">ascii</td>
941 <td>character codes 0 - 127</td>
942 </tr>
943 <tr>
944 <td align="center">blank</td>
945 <td>space or tab only</td>
946 </tr>
947 <tr>
948 <td align="center">cntrl</td>
949 <td>control characters</td>
950 </tr>
951 <tr>
952 <td align="center">digit</td>
953 <td>decimal digits (same as \d)</td>
954 </tr>
955 <tr>
956 <td align="center">graph</td>
957 <td>printing characters, excluding space</td>
958 </tr>
959 <tr>
960 <td align="center">lower</td>
961 <td>lower case letters</td>
962 </tr>
963 <tr>
964 <td align="center">print</td>
965 <td>printing characters, including space</td>
966 </tr>
967 <tr>
968 <td align="center">punct</td>
969 <td>printing characters, excluding letters and digits</td>
970 </tr>
971 <tr>
972 <td align="center">space</td>
973 <td>white space (not quite the same as \s)</td>
974 </tr>
975 <tr>
976 <td align="center">upper</td>
977 <td>upper case letters</td>
978 </tr>
979 <tr>
980 <td align="center">word</td>
981 <td>"word" characters (same as \w)</td>
982 </tr>
983 <tr>
984 <td align="center">xdigit</td>
985 <td>hexadecimal digits</td>
986 </tr>
987 </tbody>
988 </table></div>
989 </div>
990 <br class="table-break"><p>
991 The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13),
992 and space (32). Notice that this list includes the VT character (code
993 11). This makes "space" different to \s, which does not include VT (for
994 Perl compatibility).
995 </p>
996 <p>
997 The name "word" is a Perl extension, and "blank" is a GNU extension.
998 Another Perl extension is negation, which is indicated by a ^ character
999 after the colon. For example,
1000 </p>
1001 <pre class="programlisting">
1002 [12[:^digit:]]
1003 </pre>
1004 <p>
1005 matches "1", "2", or any non-digit. GRegex also recognize the
1006 POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but
1007 these are not supported, and an error is given if they are encountered.
1008 </p>
1009 <p>
1010 In UTF-8 mode, characters with values greater than 128 do not match any
1011 of the POSIX character classes.
1012 </p>
1013 </div>
1014 <div class="refsect1">
1015 <a name="id722959"></a><h2>Vertical bar</h2>
1016 <p>
1017 Vertical bar characters are used to separate alternative patterns. For
1018 example, the pattern
1019 </p>
1020 <pre class="programlisting">
1021  gilbert|sullivan
1022 </pre>
1023 <p>
1024 matches either "gilbert" or "sullivan". Any number of alternatives may
1025 appear, and an empty alternative is permitted (matching the empty
1026 string). The matching process tries each alternative in turn, from
1027 left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern.
1028 </p>
1029 </div>
1030 <div class="refsect1">
1031 <a name="id722984"></a><h2>Internal option setting</h2>
1032 <p>
1033 The settings of the <code class="varname">G_REGEX_CASELESS</code>, <code class="varname">G_REGEX_MULTILINE</code>, <code class="varname">G_REGEX_MULTILINE</code>,
1034 and <code class="varname">G_REGEX_EXTENDED</code> options can be changed from within the pattern by a
1035 sequence of Perl-style option letters enclosed between "(?" and ")". The
1036 option letters are
1037 </p>
1038 <div class="table">
1039 <a name="id723010"></a><p class="title"><b>Table 10. Option settings</b></p>
1040 <div class="table-contents"><table summary="Option settings" border="1">
1041 <colgroup>
1042 <col align="center">
1043 <col>
1044 </colgroup>
1045 <thead><tr>
1046 <th align="center">Option</th>
1047 <th>Flag</th>
1048 </tr></thead>
1049 <tbody>
1050 <tr>
1051 <td align="center">i</td>
1052 <td><code class="varname">G_REGEX_CASELESS</code></td>
1053 </tr>
1054 <tr>
1055 <td align="center">m</td>
1056 <td><code class="varname">G_REGEX_MULTILINE</code></td>
1057 </tr>
1058 <tr>
1059 <td align="center">s</td>
1060 <td><code class="varname">G_REGEX_DOTALL</code></td>
1061 </tr>
1062 <tr>
1063 <td align="center">x</td>
1064 <td><code class="varname">G_REGEX_EXTENDED</code></td>
1065 </tr>
1066 </tbody>
1067 </table></div>
1068 </div>
1069 <br class="table-break"><p>
1070 For example, (?im) sets caseless, multiline matching. It is also
1071 possible to unset these options by preceding the letter with a hyphen, and a
1072 combined setting and unsetting such as (?im-sx), which sets <code class="varname">G_REGEX_CASELESS</code>
1073 and <code class="varname">G_REGEX_MULTILINE</code> while unsetting <code class="varname">G_REGEX_DOTALL</code> and <code class="varname">G_REGEX_EXTENDED</code>,
1074 is also permitted. If a letter appears both before and after the
1075 hyphen, the option is unset.
1076 </p>
1077 <p>
1078 When an option change occurs at top level (that is, not inside subpattern
1079 parentheses), the change applies to the remainder of the pattern
1080 that follows.
1081 </p>
1082 <p>
1083 An option change within a subpattern (see below for a description of subpatterns)
1084 affects only that part of the current pattern that follows it, so
1085 </p>
1086 <pre class="programlisting">
1087 (a(?i)b)c
1088 </pre>
1089 <p>
1090 matches abc and aBc and no other strings (assuming <code class="varname">G_REGEX_CASELESS</code> is not
1091 used). By this means, options can be made to have different settings
1092 in different parts of the pattern. Any changes made in one alternative
1093 do carry on into subsequent branches within the same subpattern. For
1094 example,
1095 </p>
1096 <pre class="programlisting">
1097 (a(?i)b|c)
1098 </pre>
1099 <p>
1100 matches "ab", "aB", "c", and "C", even though when matching "C" the
1101 first branch is abandoned before the option setting. This is because
1102 the effects of option settings happen at compile time. There would be
1103 some very weird behaviour otherwise.
1104 </p>
1105 <p>
1106 The options <code class="varname">G_REGEX_UNGREEDY</code> and
1107 <code class="varname">G_REGEX_EXTRA</code> and <code class="varname">G_REGEX_DUPNAMES</code>
1108 can be changed in the same way as the Perl-compatible options by using
1109 the characters U, X and J respectively.
1110 </p>
1111 </div>
1112 <div class="refsect1">
1113 <a name="id723179"></a><h2>Subpatterns</h2>
1114 <p>
1115 Subpatterns are delimited by parentheses (round brackets), which can be
1116 nested. Turning part of a pattern into a subpattern does two things:
1117 </p>
1118 <div class="itemizedlist"><ul class="itemizedlist" type="disc">
1119 <li class="listitem"><p>
1120 It localizes a set of alternatives. For example, the pattern
1121 cat(aract|erpillar|) matches one of the words "cat", "cataract", or
1122 "caterpillar". Without the parentheses, it would match "cataract",
1123 "erpillar" or an empty string.
1124 </p></li>
1125 <li class="listitem"><p>
1126 It sets up the subpattern as a capturing subpattern. This means
1127 that, when the whole pattern matches, that portion of the
1128 string that matched the subpattern can be obtained using <code class="function">g_match_info_fetch()</code>.
1129 Opening parentheses are counted from left to right (starting from 1, as
1130 subpattern 0 is the whole matched string) to obtain numbers for the
1131 capturing subpatterns.
1132 </p></li>
1133 </ul></div>
1134 <p>
1135 For example, if the string "the red king" is matched against the pattern
1136 </p>
1137 <pre class="programlisting">
1138 the ((red|white) (king|queen))
1139 </pre>
1140 <p>
1141 the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3, respectively.
1142 </p>
1143 <p>
1144 The fact that plain parentheses fulfil two functions is not always
1145 helpful. There are often times when a grouping subpattern is required
1146 without a capturing requirement. If an opening parenthesis is followed
1147 by a question mark and a colon, the subpattern does not do any capturing,
1148 and is not counted when computing the number of any subsequent
1149 capturing subpatterns. For example, if the string "the white queen" is
1150 matched against the pattern
1151 </p>
1152 <pre class="programlisting">
1153 the ((?:red|white) (king|queen))
1154 </pre>
1155 <p>
1156 the captured substrings are "white queen" and "queen", and are numbered
1157 1 and 2. The maximum number of capturing subpatterns is 65535.
1158 </p>
1159 <p>
1160 As a convenient shorthand, if any option settings are required at the
1161 start of a non-capturing subpattern, the option letters may appear
1162 between the "?" and the ":". Thus the two patterns
1163 </p>
1164 <pre class="programlisting">
1165 (?i:saturday|sunday)
1166 (?:(?i)saturday|sunday)
1167 </pre>
1168 <p>
1169 match exactly the same set of strings. Because alternative branches are
1170 tried from left to right, and options are not reset until the end of
1171 the subpattern is reached, an option setting in one branch does affect
1172 subsequent branches, so the above patterns match "SUNDAY" as well as
1173 "Saturday".
1174 </p>
1175 </div>
1176 <div class="refsect1">
1177 <a name="id723264"></a><h2>Named subpatterns</h2>
1178 <p>
1179 Identifying capturing parentheses by number is simple, but it can be
1180 very hard to keep track of the numbers in complicated regular expressions.
1181 Furthermore, if an expression is modified, the numbers may
1182 change. To help with this difficulty, GRegex supports the naming of
1183 subpatterns.  A subpattern can be named in one of three ways: (?&lt;name&gt;...) or
1184 (?'name'...) as in Perl, or (?P&lt;name&gt;...) as in Python.
1185 References to capturing parentheses from other
1186 parts of the pattern, such as backreferences, recursion, and conditions,
1187 can be made by name as well as by number.
1188 </p>
1189 <p>
1190 Names consist of up to 32 alphanumeric characters and underscores. Named
1191 capturing parentheses are still allocated numbers as well as names, exactly as
1192 if the names were not present.
1193 By default, a name must be unique within a pattern, but it is possible to relax
1194 this constraint by setting the <code class="varname">G_REGEX_DUPNAMES</code> option at
1195 compile time. This can be useful for patterns where only one instance of the
1196 named parentheses can match. Suppose you want to match the name of a weekday,
1197 either as a 3-letter abbreviation or as the full name, and in both cases you
1198 want to extract the abbreviation. This pattern (ignoring the line breaks) does
1199 the job:
1200 </p>
1201 <pre class="programlisting">
1202 (?&lt;DN&gt;Mon|Fri|Sun)(?:day)?|
1203 (?&lt;DN&gt;Tue)(?:sday)?|
1204 (?&lt;DN&gt;Wed)(?:nesday)?|
1205 (?&lt;DN&gt;Thu)(?:rsday)?|
1206 (?&lt;DN&gt;Sat)(?:urday)?
1207 </pre>
1208 <p>
1209 There are five capturing substrings, but only one is ever set after a match.
1210 The function for extracting the data by name returns the substring
1211 for the first (and in this example, the only) subpattern of that name that
1212 matched. This saves searching to find which numbered subpattern it was. If you
1213 make a reference to a non-unique named subpattern from elsewhere in the
1214 pattern, the one that corresponds to the lowest number is used.
1215 </p>
1216 </div>
1217 <div class="refsect1">
1218 <a name="id723306"></a><h2>Repetition</h2>
1219 <p>
1220 Repetition is specified by quantifiers, which can follow any of the
1221 following items:
1222 </p>
1223 <div class="itemizedlist"><ul class="itemizedlist" type="disc">
1224 <li class="listitem"><p>a literal data character</p></li>
1225 <li class="listitem"><p>the dot metacharacter</p></li>
1226 <li class="listitem"><p>the \C escape sequence</p></li>
1227 <li class="listitem"><p>the \X escape sequence (in UTF-8 mode)</p></li>
1228 <li class="listitem"><p>the \R escape sequence</p></li>
1229 <li class="listitem"><p>an escape such as \d that matches a single character</p></li>
1230 <li class="listitem"><p>a character class</p></li>
1231 <li class="listitem"><p>a back reference (see next section)</p></li>
1232 <li class="listitem"><p>a parenthesized subpattern (unless it is an assertion)</p></li>
1233 </ul></div>
1234 <p>
1235 The general repetition quantifier specifies a minimum and maximum number
1236 of permitted matches, by giving the two numbers in curly brackets
1237 (braces), separated by a comma. The numbers must be less than 65536,
1238 and the first must be less than or equal to the second. For example:
1239 </p>
1240 <pre class="programlisting">
1241 z{2,4}
1242 </pre>
1243 <p>
1244 matches "zz", "zzz", or "zzzz". A closing brace on its own is not a
1245 special character. If the second number is omitted, but the comma is
1246 present, there is no upper limit; if the second number and the comma
1247 are both omitted, the quantifier specifies an exact number of required
1248 matches. Thus
1249 </p>
1250 <pre class="programlisting">
1251 [aeiou]{3,}
1252 </pre>
1253 <p>
1254 matches at least 3 successive vowels, but may match many more, while
1255 </p>
1256 <pre class="programlisting">
1257 \d{8}
1258 </pre>
1259 <p>
1260 matches exactly 8 digits. An opening curly bracket that appears in a
1261 position where a quantifier is not allowed, or one that does not match
1262 the syntax of a quantifier, is taken as a literal character. For example,
1263 {,6} is not a quantifier, but a literal string of four characters.
1264 </p>
1265 <p>
1266 In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to
1267 individual bytes. Thus, for example, \x{100}{2} matches two UTF-8
1268 characters, each of which is represented by a two-byte sequence. Similarly,
1269 \X{3} matches three Unicode extended sequences, each of which may be
1270 several bytes long (and they may be of different lengths).
1271 </p>
1272 <p>
1273 The quantifier {0} is permitted, causing the expression to behave as if
1274 the previous item and the quantifier were not present.
1275 </p>
1276 <p>
1277 For convenience, the three most common quantifiers have single-character
1278 abbreviations:
1279 </p>
1280 <div class="table">
1281 <a name="id723418"></a><p class="title"><b>Table 11. Abbreviations for quantifiers</b></p>
1282 <div class="table-contents"><table summary="Abbreviations for quantifiers" border="1">
1283 <colgroup>
1284 <col align="center">
1285 <col>
1286 </colgroup>
1287 <thead><tr>
1288 <th align="center">Abbreviation</th>
1289 <th>Meaning</th>
1290 </tr></thead>
1291 <tbody>
1292 <tr>
1293 <td align="center">*</td>
1294 <td>is equivalent to {0,}</td>
1295 </tr>
1296 <tr>
1297 <td align="center">+</td>
1298 <td>is equivalent to {1,}</td>
1299 </tr>
1300 <tr>
1301 <td align="center">?</td>
1302 <td>is equivalent to {0,1}</td>
1303 </tr>
1304 </tbody>
1305 </table></div>
1306 </div>
1307 <br class="table-break"><p>
1308 It is possible to construct infinite loops by following a subpattern
1309 that can match no characters with a quantifier that has no upper limit,
1310 for example:
1311 </p>
1312 <pre class="programlisting">
1313 (a?)*
1314 </pre>
1315 <p>
1316 Because there are cases where this can be useful, such patterns are
1317 accepted, but if any repetition of the subpattern does in fact match
1318 no characters, the loop is forcibly broken.
1319 </p>
1320 <p>
1321 By default, the quantifiers are "greedy", that is, they match as much
1322 as possible (up to the maximum number of permitted times), without
1323 causing the rest of the pattern to fail. The classic example of where
1324 this gives problems is in trying to match comments in C programs. These
1325 appear between /* and */ and within the comment, individual * and /
1326 characters may appear. An attempt to match C comments by applying the
1327 pattern
1328 </p>
1329 <pre class="programlisting">
1330 /\*.*\*/
1331 </pre>
1332 <p>
1333 to the string
1334 </p>
1335 <pre class="programlisting">
1336 /* first comment */  not comment  /* second comment */
1337 </pre>
1338 <p>
1339 fails, because it matches the entire string owing to the greediness of
1340 the .* item.
1341 </p>
1342 <p>
1343 However, if a quantifier is followed by a question mark, it ceases to
1344 be greedy, and instead matches the minimum number of times possible, so
1345 the pattern
1346 </p>
1347 <pre class="programlisting">
1348 /\*.*?\*/
1349 </pre>
1350 <p>
1351 does the right thing with the C comments. The meaning of the various
1352 quantifiers is not otherwise changed, just the preferred number of
1353 matches. Do not confuse this use of question mark with its use as a
1354 quantifier in its own right. Because it has two uses, it can sometimes
1355 appear doubled, as in
1356 </p>
1357 <pre class="programlisting">
1358 \d??\d
1359 </pre>
1360 <p>
1361 which matches one digit by preference, but can match two if that is the
1362 only way the rest of the pattern matches.
1363 </p>
1364 <p>
1365 If the <code class="varname">G_REGEX_UNGREEDY</code> flag is set, the quantifiers are not greedy
1366 by default, but individual ones can be made greedy by following them with
1367 a question mark. In other words, it inverts the default behaviour.
1368 </p>
1369 <p>
1370 When a parenthesized subpattern is quantified with a minimum repeat
1371 count that is greater than 1 or with a limited maximum, more memory is
1372 required for the compiled pattern, in proportion to the size of the
1373 minimum or maximum.
1374 </p>
1375 <p>
1376 If a pattern starts with .* or .{0,} and the <code class="varname">G_REGEX_DOTALL</code> flag
1377 is set, thus allowing the dot to match newlines, the
1378 pattern is implicitly anchored, because whatever follows will be tried
1379 against every character position in the string, so there is no
1380 point in retrying the overall match at any position after the first.
1381 GRegex normally treats such a pattern as though it were preceded by \A.
1382 </p>
1383 <p>
1384 In cases where it is known that the string contains no newlines, it
1385 is worth setting <code class="varname">G_REGEX_DOTALL</code> in order to obtain this optimization,
1386 or alternatively using ^ to indicate anchoring explicitly.
1387 </p>
1388 <p>
1389 However, there is one situation where the optimization cannot be used.
1390 When .* is inside capturing parentheses that are the subject of a
1391 backreference elsewhere in the pattern, a match at the start may fail
1392 where a later one succeeds. Consider, for example:
1393 </p>
1394 <pre class="programlisting">
1395 (.*)abc\1
1396 </pre>
1397 <p>
1398 If the string is "xyz123abc123" the match point is the fourth character.
1399 For this reason, such a pattern is not implicitly anchored.
1400 </p>
1401 <p>
1402 When a capturing subpattern is repeated, the value captured is the
1403 substring that matched the final iteration. For example, after
1404 </p>
1405 <pre class="programlisting">
1406 (tweedle[dume]{3}\s*)+
1407 </pre>
1408 <p>
1409 has matched "tweedledum tweedledee" the value of the captured substring
1410 is "tweedledee". However, if there are nested capturing subpatterns,
1411 the corresponding captured values may have been set in previous iterations.
1412 For example, after
1413 </p>
1414 <pre class="programlisting">
1415 /(a|(b))+/
1416 </pre>
1417 <p>
1418 matches "aba" the value of the second captured substring is "b".
1419 </p>
1420 </div>
1421 <div class="refsect1">
1422 <a name="id723643"></a><h2>Atomic grouping and possessive quantifiers</h2>
1423 <p>
1424 With both maximizing ("greedy") and minimizing ("ungreedy" or "lazy")
1425 repetition, failure of what follows normally causes the repeated
1426 item to be re-evaluated to see if a different number
1427 of repeats allows the rest of the pattern to match. Sometimes it
1428 is useful to prevent this, either to change the nature of the
1429 match, or to cause it fail earlier than it otherwise might, when the
1430 author of the pattern knows there is no point in carrying on.
1431 </p>
1432 <p>
1433 Consider, for example, the pattern \d+foo when applied to the string
1434 </p>
1435 <pre class="programlisting">
1436 123456bar
1437 </pre>
1438 <p>
1439 After matching all 6 digits and then failing to match "foo", the normal
1440 action of the matcher is to try again with only 5 digits matching the
1441 \d+ item, and then with 4, and so on, before ultimately failing.
1442 "Atomic grouping" (a term taken from Jeffrey Friedl’s book) provides
1443 the means for specifying that once a subpattern has matched, it is not
1444 to be re-evaluated in this way.
1445 </p>
1446 <p>
1447 If we use atomic grouping for the previous example, the matcher
1448 give up immediately on failing to match "foo" the first time. The notation
1449 is a kind of special parenthesis, starting with (?&gt; as in this
1450 example:
1451 </p>
1452 <pre class="programlisting">
1453 (?&gt;\d+)foo
1454 </pre>
1455 <p>
1456 This kind of parenthesis "locks up" the part of the pattern it contains
1457 once it has matched, and a failure further into the pattern is
1458 prevented from backtracking into it. Backtracking past it to previous
1459 items, however, works as normal.
1460 </p>
1461 <p>
1462 An alternative description is that a subpattern of this type matches
1463 the string of characters that an identical standalone pattern would
1464 match, if anchored at the current point in the string.
1465 </p>
1466 <p>
1467 Atomic grouping subpatterns are not capturing subpatterns. Simple cases
1468 such as the above example can be thought of as a maximizing repeat that
1469 must swallow everything it can. So, while both \d+ and \d+? are prepared
1470 to adjust the number of digits they match in order to make the
1471 rest of the pattern match, (?&gt;\d+) can only match an entire sequence of
1472 digits.
1473 </p>
1474 <p>
1475 Atomic groups in general can of course contain arbitrarily complicated
1476 subpatterns, and can be nested. However, when the subpattern for an
1477 atomic group is just a single repeated item, as in the example above, a
1478 simpler notation, called a "possessive quantifier" can be used. This
1479 consists of an additional + character following a quantifier. Using
1480 this notation, the previous example can be rewritten as
1481 </p>
1482 <pre class="programlisting">
1483 \d++foo
1484 </pre>
1485 <p>
1486 Possessive quantifiers are always greedy; the setting of the
1487 <code class="varname">G_REGEX_UNGREEDY</code> option is ignored. They are a convenient notation for the
1488 simpler forms of atomic group. However, there is no difference in the
1489 meaning of a possessive quantifier and the equivalent
1490 atomic group, though there may be a performance difference;
1491 possessive quantifiers should be slightly faster.
1492 </p>
1493 <p>
1494 The possessive quantifier syntax is an extension to the Perl syntax.
1495 It was invented by Jeffrey Friedl in the first edition of his book and
1496 then implemented by Mike McCloskey in Sun's Java package.
1497 It ultimately found its way into Perl at release 5.10.
1498 </p>
1499 <p>
1500 GRegex has an optimization that automatically "possessifies" certain simple
1501 pattern constructs. For example, the sequence A+B is treated as A++B because
1502 there is no point in backtracking into a sequence of A's when B must follow.
1503 </p>
1504 <p>
1505 When a pattern contains an unlimited repeat inside a subpattern that
1506 can itself be repeated an unlimited number of times, the use of an
1507 atomic group is the only way to avoid some failing matches taking a
1508 very long time indeed. The pattern
1509 </p>
1510 <pre class="programlisting">
1511 (\D+|&lt;\d+&gt;)*[!?]
1512 </pre>
1513 <p>
1514 matches an unlimited number of substrings that either consist of non-
1515 digits, or digits enclosed in &lt;&gt;, followed by either ! or ?. When it
1516 matches, it runs quickly. However, if it is applied to
1517 </p>
1518 <pre class="programlisting">
1519 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1520 </pre>
1521 <p>
1522 it takes a long time before reporting failure. This is because the
1523 string can be divided between the internal \D+ repeat and the external
1524 * repeat in a large number of ways, and all have to be tried. (The
1525 example uses [!?] rather than a single character at the end, because
1526 GRegex has an optimization that allows for fast failure
1527 when a single character is used. It remember the last single character
1528 that is required for a match, and fail early if it is not present
1529 in the string.) If the pattern is changed so that it uses an atomic
1530 group, like this:
1531 </p>
1532 <pre class="programlisting">
1533 ((?&gt;\D+)|&lt;\d+&gt;)*[!?]
1534 </pre>
1535 <p>
1536 sequences of non-digits cannot be broken, and failure happens quickly.
1537 </p>
1538 </div>
1539 <div class="refsect1">
1540 <a name="id727984"></a><h2>Back references</h2>
1541 <p>
1542 Outside a character class, a backslash followed by a digit greater than
1543 0 (and possibly further digits) is a back reference to a capturing subpattern
1544 earlier (that is, to its left) in the pattern, provided there have been that
1545 many previous capturing left parentheses.
1546 </p>
1547 <p>
1548 However, if the decimal number following the backslash is less than 10,
1549 it is always taken as a back reference, and causes an error only if
1550 there are not that many capturing left parentheses in the entire pattern.
1551 In other words, the parentheses that are referenced need not be
1552 to the left of the reference for numbers less than 10. A "forward back
1553 reference" of this type can make sense when a repetition is involved and
1554 the subpattern to the right has participated in an earlier iteration.
1555 </p>
1556 <p>
1557 It is not possible to have a numerical "forward back reference" to subpattern
1558 whose number is 10 or more using this syntax because a sequence such as \e50 is
1559 interpreted as a character defined in octal. See the subsection entitled
1560 "Non-printing characters" above for further details of the handling of digits
1561 following a backslash. There is no such problem when named parentheses are used.
1562 A back reference to any subpattern is possible using named parentheses (see below).
1563 </p>
1564 <p>
1565 Another way of avoiding the ambiguity inherent in the use of digits following a
1566 backslash is to use the \g escape sequence (introduced in Perl 5.10.)
1567 This escape must be followed by a positive or a negative number,
1568 optionally enclosed in braces.
1569 </p>
1570 <p>
1571 A positive number specifies an absolute reference without the ambiguity that is
1572 present in the older syntax. It is also useful when literal digits follow the
1573 reference. A negative number is a relative reference. Consider "(abc(def)ghi)\g{-1}",
1574 the sequence \g{-1} is a reference to the most recently started capturing
1575 subpattern before \g, that is, is it equivalent to \2. Similarly, \g{-2}
1576 would be equivalent to \1. The use of relative references can be helpful in
1577 long patterns, and also in patterns that are created by joining together
1578 fragments that contain references within themselves.
1579 </p>
1580 <p>
1581 A back reference matches whatever actually matched the capturing subpattern
1582 in the current string, rather than anything matching
1583 the subpattern itself (see "Subpatterns as subroutines" below for a way
1584 of doing that). So the pattern
1585 </p>
1586 <pre class="programlisting">
1587 (sens|respons)e and \1ibility
1588 </pre>
1589 <p>
1590 matches "sense and sensibility" and "response and responsibility", but
1591 not "sense and responsibility". If caseful matching is in force at the
1592 time of the back reference, the case of letters is relevant. For example,
1593 </p>
1594 <pre class="programlisting">
1595 ((?i)rah)\s+\1
1596 </pre>
1597 <p>
1598 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the
1599 original capturing subpattern is matched caselessly.
1600 </p>
1601 <p>
1602 Back references to named subpatterns use the Perl syntax \k&lt;name&gt; or \k'name'
1603 or the Python syntax (?P=name). We could rewrite the above example in either of
1604 the following ways:
1605 </p>
1606 <pre class="programlisting">
1607 (?&lt;p1&gt;(?i)rah)\s+\k&lt;p1&gt;
1608 (?P&lt;p1&gt;(?i)rah)\s+(?P=p1)
1609 </pre>
1610 <p>
1611 A subpattern that is referenced by name may appear in the pattern before or
1612 after the reference.
1613 </p>
1614 <p>
1615 There may be more than one back reference to the same subpattern. If a
1616 subpattern has not actually been used in a particular match, any back
1617 references to it always fail. For example, the pattern
1618 </p>
1619 <pre class="programlisting">
1620 (a|(bc))\2
1621 </pre>
1622 <p>
1623 always fails if it starts to match "a" rather than "bc". Because there
1624 may be many capturing parentheses in a pattern, all digits following
1625 the backslash are taken as part of a potential back reference number.
1626 If the pattern continues with a digit character, some delimiter must be
1627 used to terminate the back reference. If the <code class="varname">G_REGEX_EXTENDED</code> flag is
1628 set, this can be whitespace. Otherwise an empty comment (see "Comments" below) can be used.
1629 </p>
1630 <p>
1631 A back reference that occurs inside the parentheses to which it refers
1632 fails when the subpattern is first used, so, for example, (a\1) never
1633 matches. However, such references can be useful inside repeated subpatterns.
1634 For example, the pattern
1635 </p>
1636 <pre class="programlisting">
1637 (a|b\1)+
1638 </pre>
1639 <p>
1640 matches any number of "a"s and also "aba", "ababbaa" etc. At each iteration
1641 of the subpattern, the back reference matches the character
1642 string corresponding to the previous iteration. In order for this to
1643 work, the pattern must be such that the first iteration does not need
1644 to match the back reference. This can be done using alternation, as in
1645 the example above, or by a quantifier with a minimum of zero.
1646 </p>
1647 </div>
1648 <div class="refsect1">
1649 <a name="id728111"></a><h2>Assertions</h2>
1650 <p>
1651 An assertion is a test on the characters following or preceding the
1652 current matching point that does not actually consume any characters.
1653 The simple assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are
1654 described above.
1655 </p>
1656 <p>
1657 More complicated assertions are coded as subpatterns. There are two
1658 kinds: those that look ahead of the current position in the
1659 string, and those that look behind it. An assertion subpattern is
1660 matched in the normal way, except that it does not cause the current
1661 matching position to be changed.
1662 </p>
1663 <p>
1664 Assertion subpatterns are not capturing subpatterns, and may not be
1665 repeated, because it makes no sense to assert the same thing several
1666 times. If any kind of assertion contains capturing subpatterns within
1667 it, these are counted for the purposes of numbering the capturing
1668 subpatterns in the whole pattern. However, substring capturing is carried
1669 out only for positive assertions, because it does not make sense for
1670 negative assertions.
1671 </p>
1672 <div class="refsect2">
1673 <a name="id728136"></a><h3>Lookahead assertions</h3>
1674 <p>
1675 Lookahead assertions start with (?= for positive assertions and (?! for
1676 negative assertions. For example,
1677 </p>
1678 <pre class="programlisting">
1679 \w+(?=;)
1680 </pre>
1681 <p>
1682 matches a word followed by a semicolon, but does not include the semicolon
1683 in the match, and
1684 </p>
1685 <pre class="programlisting">
1686 foo(?!bar)
1687 </pre>
1688 <p>
1689 matches any occurrence of "foo" that is not followed by "bar". Note
1690 that the apparently similar pattern
1691 </p>
1692 <pre class="programlisting">
1693 (?!foo)bar
1694 </pre>
1695 <p>
1696 does not find an occurrence of "bar" that is preceded by something
1697 other than "foo"; it finds any occurrence of "bar" whatsoever, because
1698 the assertion (?!foo) is always true when the next three characters are
1699 "bar". A lookbehind assertion is needed to achieve the other effect.
1700 </p>
1701 <p>
1702 If you want to force a matching failure at some point in a pattern, the
1703 most convenient way to do it is with (?!) because an empty string
1704 always matches, so an assertion that requires there not to be an empty
1705 string must always fail.
1706 </p>
1707 </div>
1708 <hr>
1709 <div class="refsect2">
1710 <a name="id728186"></a><h3>Lookbehind assertions</h3>
1711 <p>
1712 Lookbehind assertions start with (?&lt;= for positive assertions and (?&lt;!
1713 for negative assertions. For example,
1714 </p>
1715 <pre class="programlisting">
1716 (?&lt;!foo)bar
1717 </pre>
1718 <p>
1719 does find an occurrence of "bar" that is not preceded by "foo". The
1720 contents of a lookbehind assertion are restricted such that all the
1721 strings it matches must have a fixed length. However, if there are
1722 several top-level alternatives, they do not all have to have the same
1723 fixed length. Thus
1724 </p>
1725 <pre class="programlisting">
1726 (?&lt;=bullock|donkey)
1727 </pre>
1728 <p>
1729 is permitted, but
1730 </p>
1731 <pre class="programlisting">
1732 (?&lt;!dogs?|cats?)
1733 </pre>
1734 <p>
1735 causes an error at compile time. Branches that match different length
1736 strings are permitted only at the top level of a lookbehind assertion.
1737 An assertion such as
1738 </p>
1739 <pre class="programlisting">
1740 (?&lt;=ab(c|de))
1741 </pre>
1742 <p>
1743 is not permitted, because its single top-level branch can match two
1744 different lengths, but it is acceptable if rewritten to use two top-
1745 level branches:
1746 </p>
1747 <pre class="programlisting">
1748 (?&lt;=abc|abde)
1749 </pre>
1750 <p>
1751 The implementation of lookbehind assertions is, for each alternative,
1752 to temporarily move the current position back by the fixed length and
1753 then try to match. If there are insufficient characters before the
1754 current position, the assertion fails.
1755 </p>
1756 <p>
1757 GRegex does not allow the \C escape (which matches a single byte in UTF-8
1758 mode) to appear in lookbehind assertions, because it makes it impossible
1759 to calculate the length of the lookbehind. The \X and \R escapes, which can
1760 match different numbers of bytes, are also not permitted.
1761 </p>
1762 <p>
1763 Possessive quantifiers can be used in conjunction with lookbehind assertions to
1764 specify efficient matching at the end of the subject string. Consider a simple
1765 pattern such as
1766 </p>
1767 <pre class="programlisting">
1768 abcd$
1769 </pre>
1770 <p>
1771 when applied to a long string that does not match. Because matching
1772 proceeds from left to right, GRegex will look for each "a" in the string
1773 and then see if what follows matches the rest of the pattern. If the
1774 pattern is specified as
1775 </p>
1776 <pre class="programlisting">
1777 ^.*abcd$
1778 </pre>
1779 <p>
1780 the initial .* matches the entire string at first, but when this fails
1781 (because there is no following "a"), it backtracks to match all but the
1782 last character, then all but the last two characters, and so on. Once
1783 again the search for "a" covers the entire string, from right to left,
1784 so we are no better off. However, if the pattern is written as
1785 </p>
1786 <pre class="programlisting">
1787 ^.*+(?&lt;=abcd)
1788 </pre>
1789 <p>
1790 there can be no backtracking for the .*+ item; it can match only the
1791 entire string. The subsequent lookbehind assertion does a single test
1792 on the last four characters. If it fails, the match fails immediately.
1793 For long strings, this approach makes a significant difference to the
1794 processing time.
1795 </p>
1796 </div>
1797 <hr>
1798 <div class="refsect2">
1799 <a name="id728301"></a><h3>Using multiple assertions</h3>
1800 <p>
1801 Several assertions (of any sort) may occur in succession. For example,
1802 </p>
1803 <pre class="programlisting">
1804 (?&lt;=\d{3})(?&lt;!999)foo
1805 </pre>
1806 <p>
1807 matches "foo" preceded by three digits that are not "999". Notice that
1808 each of the assertions is applied independently at the same point in
1809 the string. First there is a check that the previous three
1810 characters are all digits, and then there is a check that the same
1811 three characters are not "999". This pattern does not match "foo" preceded
1812 by six characters, the first of which are digits and the last
1813 three of which are not "999". For example, it doesn’t match "123abcfoo".
1814 A pattern to do that is
1815 </p>
1816 <pre class="programlisting">
1817 (?&lt;=\d{3}...)(?&lt;!999)foo
1818 </pre>
1819 <p>
1820 This time the first assertion looks at the preceding six characters,
1821 checking that the first three are digits, and then the second assertion
1822 checks that the preceding three characters are not "999".
1823 </p>
1824 <p>
1825 Assertions can be nested in any combination. For example,
1826 </p>
1827 <pre class="programlisting">
1828 (?&lt;=(?&lt;!foo)bar)baz
1829 </pre>
1830 <p>
1831 matches an occurrence of "baz" that is preceded by "bar" which in turn
1832 is not preceded by "foo", while
1833 </p>
1834 <pre class="programlisting">
1835 (?&lt;=\d{3}(?!999)...)foo
1836 </pre>
1837 <p>
1838 is another pattern that matches "foo" preceded by three digits and any
1839 three characters that are not "999".
1840 </p>
1841 </div>
1842 </div>
1843 <div class="refsect1">
1844 <a name="id728363"></a><h2>Conditional subpatterns</h2>
1845 <p>
1846 It is possible to cause the matching process to obey a subpattern
1847 conditionally or to choose between two alternative subpatterns, depending
1848 on the result of an assertion, or whether a previous capturing subpattern
1849 matched or not. The two possible forms of conditional subpattern are
1850 </p>
1851 <pre class="programlisting">
1852 (?(condition)yes-pattern)
1853 (?(condition)yes-pattern|no-pattern)
1854 </pre>
1855 <p>
1856 If the condition is satisfied, the yes-pattern is used; otherwise the
1857 no-pattern (if present) is used. If there are more than two alternatives
1858 in the subpattern, a compile-time error occurs.
1859 </p>
1860 <p>
1861 There are four kinds of condition: references to subpatterns, references to
1862 recursion, a pseudo-condition called DEFINE, and assertions.
1863 </p>
1864 <div class="refsect2">
1865 <a name="id728391"></a><h3>Checking for a used subpattern by number</h3>
1866 <p>
1867 If the text between the parentheses consists of a sequence of digits, the
1868 condition is true if the capturing subpattern of that number has previously
1869 matched.
1870 </p>
1871 <p>
1872 Consider the following pattern, which contains non-significant white space
1873 to make it more readable (assume the <code class="varname">G_REGEX_EXTENDED</code>)
1874 and to divide it into three parts for ease of discussion:
1875 </p>
1876 <pre class="programlisting">
1877 ( \( )?    [^()]+    (?(1) \) )
1878 </pre>
1879 <p>
1880 The first part matches an optional opening parenthesis, and if that
1881 character is present, sets it as the first captured substring. The second
1882 part matches one or more characters that are not parentheses. The
1883 third part is a conditional subpattern that tests whether the first set
1884 of parentheses matched or not. If they did, that is, if string started
1885 with an opening parenthesis, the condition is true, and so the yes-pattern
1886 is executed and a closing parenthesis is required. Otherwise,
1887 since no-pattern is not present, the subpattern matches nothing. In
1888 other words, this pattern matches a sequence of non-parentheses,
1889 optionally enclosed in parentheses.
1890 </p>
1891 </div>
1892 <hr>
1893 <div class="refsect2">
1894 <a name="id728426"></a><h3>Checking for a used subpattern by name</h3>
1895 <p>
1896 Perl uses the syntax (?(&lt;name&gt;)...) or (?('name')...) to test for a used
1897 subpattern by name, the Python syntax (?(name)...) is also recognized. However,
1898 there is a possible ambiguity with this syntax, because subpattern names may
1899 consist entirely of digits. GRegex looks first for a named subpattern; if it
1900 cannot find one and the name consists entirely of digits, GRegex looks for a
1901 subpattern of that number, which must be greater than zero. Using subpattern
1902 names that consist entirely of digits is not recommended.
1903 </p>
1904 <p>
1905 Rewriting the above example to use a named subpattern gives this:
1906 </p>
1907 <pre class="programlisting">
1908 (?&lt;OPEN&gt; \( )?    [^()]+    (?(&lt;OPEN&gt;) \) )
1909 </pre>
1910 </div>
1911 <hr>
1912 <div class="refsect2">
1913 <a name="id728451"></a><h3>Checking for pattern recursion</h3>
1914 <p>
1915 If the condition is the string (R), and there is no subpattern with the name R,
1916 the condition is true if a recursive call to the whole pattern or any
1917 subpattern has been made. If digits or a name preceded by ampersand follow the
1918 letter R, for example:
1919 </p>
1920 <pre class="programlisting">
1921 (?(R3)...)
1922 (?(R&amp;name)...)
1923 </pre>
1924 <p>
1925 the condition is true if the most recent recursion is into the subpattern whose
1926 number or name is given. This condition does not check the entire recursion
1927 stack.
1928 </p>
1929 <p>
1930 At "top level", all these recursion test conditions are false. Recursive
1931 patterns are described below.
1932 </p>
1933 </div>
1934 <hr>
1935 <div class="refsect2">
1936 <a name="id728480"></a><h3>Defining subpatterns for use by reference only</h3>
1937 <p>
1938 If the condition is the string (DEFINE), and there is no subpattern with the
1939 name DEFINE, the condition is always false. In this case, there may be only one
1940 alternative in the subpattern. It is always skipped if control reaches this
1941 point in the pattern; the idea of DEFINE is that it can be used to define
1942 "subroutines" that can be referenced from elsewhere. (The use of "subroutines"
1943 is described below.) For example, a pattern to match an IPv4 address could be
1944 written like this (ignore whitespace and line breaks):
1945 </p>
1946 <pre class="programlisting">
1947 (?(DEFINE) (?&lt;byte&gt; 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d) )
1948 \b (?&amp;byte) (\.(?&amp;byte)){3} \b
1949 </pre>
1950 <p>
1951 The first part of the pattern is a DEFINE group inside which a another group
1952 named "byte" is defined. This matches an individual component of an IPv4
1953 address (a number less than 256). When matching takes place, this part of the
1954 pattern is skipped because DEFINE acts like a false condition.
1955 </p>
1956 <p>
1957 The rest of the pattern uses references to the named group to match the four
1958 dot-separated components of an IPv4 address, insisting on a word boundary at
1959 each end.
1960 </p>
1961 </div>
1962 <hr>
1963 <div class="refsect2">
1964 <a name="id728513"></a><h3>Assertion conditions</h3>
1965 <p>
1966 If the condition is not in any of the above formats, it must be an
1967 assertion. This may be a positive or negative lookahead or lookbehind
1968 assertion. Consider this pattern, again containing non-significant
1969 white space, and with the two alternatives on the second line:
1970 </p>
1971 <pre class="programlisting">
1972 (?(?=[^a-z]*[a-z])
1973 \d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )
1974 </pre>
1975 <p>
1976 The condition is a positive lookahead assertion that matches an
1977 optional sequence of non-letters followed by a letter. In other words,
1978 it tests for the presence of at least one letter in the string. If a
1979 letter is found, the string is matched against the first alternative;
1980 otherwise it is matched against the second. This pattern matches
1981 strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are
1982 letters and dd are digits.
1983 </p>
1984 </div>
1985 </div>
1986 <div class="refsect1">
1987 <a name="id728540"></a><h2>Comments</h2>
1988 <p>
1989 The sequence (?# marks the start of a comment that continues up to the
1990 next closing parenthesis. Nested parentheses are not permitted. The
1991 characters that make up a comment play no part in the pattern matching
1992 at all.
1993 </p>
1994 <p>
1995 If the <code class="varname">G_REGEX_EXTENDED</code> option is set, an unescaped #
1996 character outside a character class introduces a comment that continues to
1997 immediately after the next newline in the pattern.
1998 </p>
1999 </div>
2000 <div class="refsect1">
2001 <a name="id728562"></a><h2>Recursive patterns</h2>
2002 <p>
2003 Consider the problem of matching a string in parentheses, allowing for
2004 unlimited nested parentheses. Without the use of recursion, the best
2005 that can be done is to use a pattern that matches up to some fixed
2006 depth of nesting. It is not possible to handle an arbitrary nesting
2007 depth.
2008 </p>
2009 <p>
2010 For some time, Perl has provided a facility that allows regular expressions to
2011 recurse (amongst other things). It does this by interpolating Perl code in the
2012 expression at run time, and the code can refer to the expression itself. A Perl
2013 pattern using code interpolation to solve the parentheses problem can be
2014 created like this:
2015 </p>
2016 <pre class="programlisting">
2017 $re = qr{\( (?: (?&gt;[^()]+) | (?p{$re}) )* \)}x;
2018 </pre>
2019 <p>
2020 The (?p{...}) item interpolates Perl code at run time, and in this case refers
2021 recursively to the pattern in which it appears.
2022 </p>
2023 <p>
2024 Obviously, GRegex cannot support the interpolation of Perl code. Instead, it
2025 supports special syntax for recursion of the entire pattern, and also for
2026 individual subpattern recursion. This kind of recursion was introduced into
2027 Perl at release 5.10.
2028 </p>
2029 <p>
2030 A special item that consists of (? followed by a number greater than zero and a
2031 closing parenthesis is a recursive call of the subpattern of the given number,
2032 provided that it occurs inside that subpattern. (If not, it is a "subroutine"
2033 call, which is described in the next section.) The special item (?R) or (?0) is
2034 a recursive call of the entire regular expression.
2035 </p>
2036 <p>
2037 In GRegex (like Python, but unlike Perl), a recursive subpattern call is always
2038 treated as an atomic group. That is, once it has matched some of the subject
2039 string, it is never re-entered, even if it contains untried alternatives and
2040 there is a subsequent matching failure.
2041 </p>
2042 <p>
2043 This pattern solves the nested parentheses problem (assume the
2044 <code class="varname">G_REGEX_EXTENDED</code> option is set so that white space is
2045 ignored):
2046 </p>
2047 <pre class="programlisting">
2048 \( ( (?&gt;[^()]+) | (?R) )* \)
2049 </pre>
2050 <p>
2051 First it matches an opening parenthesis. Then it matches any number of
2052 substrings which can either be a sequence of non-parentheses, or a
2053 recursive match of the pattern itself (that is, a correctly parenthesized
2054 substring). Finally there is a closing parenthesis.
2055 </p>
2056 <p>
2057 If this were part of a larger pattern, you would not want to recurse
2058 the entire pattern, so instead you could use this:
2059 </p>
2060 <pre class="programlisting">
2061 ( \( ( (?&gt;[^()]+) | (?1) )* \) )
2062 </pre>
2063 <p>
2064 We have put the pattern into parentheses, and caused the recursion to
2065 refer to them instead of the whole pattern. In a larger pattern, keeping
2066 track of parenthesis numbers can be tricky. It may be more convenient to
2067 use named parentheses instead.
2068 The Perl syntax for this is (?&amp;name); GRegex also supports the(?P&gt;name)
2069 syntac. We could rewrite the above example as follows:
2070 </p>
2071 <pre class="programlisting">
2072 (?&lt;pn&gt; \( ( (?&gt;[^()]+) | (?&amp;pn) )* \) )
2073 </pre>
2074 <p>
2075 If there is more than one subpattern with the same name, the earliest one is
2076 used. This particular example pattern contains nested unlimited repeats, and so
2077 the use of atomic grouping for matching strings of non-parentheses is important
2078 when applying the pattern to strings that do not match.
2079 For example, when this pattern is applied to
2080 </p>
2081 <pre class="programlisting">
2082 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
2083 </pre>
2084 <p>
2085 it yields "no match" quickly. However, if atomic grouping is not used,
2086 the match runs for a very long time indeed because there are so many
2087 different ways the + and * repeats can carve up the string, and all
2088 have to be tested before failure can be reported.
2089 </p>
2090 <p>
2091 At the end of a match, the values set for any capturing subpatterns are
2092 those from the outermost level of the recursion at which the subpattern
2093 value is set.
2094
2095
2096
2097 If the pattern above is matched against
2098 </p>
2099 <pre class="programlisting">
2100 (ab(cd)ef)
2101 </pre>
2102 <p>
2103 the value for the capturing parentheses is "ef", which is the last
2104 value taken on at the top level. If additional parentheses are added,
2105 giving
2106 </p>
2107 <pre class="programlisting">
2108 \( ( ( (?&gt;[^()]+) | (?R) )* ) \)
2109    ^                        ^
2110    ^                        ^
2111 </pre>
2112 <p>
2113 the string they capture is "ab(cd)ef", the contents of the top level
2114 parentheses.
2115 </p>
2116 <p>
2117 Do not confuse the (?R) item with the condition (R), which tests for
2118 recursion. Consider this pattern, which matches text in angle brackets,
2119 allowing for arbitrary nesting. Only digits are allowed in nested
2120 brackets (that is, when recursing), whereas any characters are permitted
2121 at the outer level.
2122 </p>
2123 <pre class="programlisting">
2124 &lt; (?: (?(R) \d++ | [^&lt;&gt;]*+) | (?R)) * &gt;
2125 </pre>
2126 <p>
2127 In this pattern, (?(R) is the start of a conditional subpattern, with
2128 two different alternatives for the recursive and non-recursive cases.
2129 The (?R) item is the actual recursive call.
2130 </p>
2131 </div>
2132 <div class="refsect1">
2133 <a name="id728717"></a><h2>Subpatterns as subroutines</h2>
2134 <p>
2135 If the syntax for a recursive subpattern reference (either by number or
2136 by name) is used outside the parentheses to which it refers, it operates
2137 like a subroutine in a programming language. The "called" subpattern may
2138 be defined before or after the reference. An earlier example pointed out
2139 that the pattern
2140 </p>
2141 <pre class="programlisting">
2142 (sens|respons)e and \1ibility
2143 </pre>
2144 <p>
2145 matches "sense and sensibility" and "response and responsibility", but
2146 not "sense and responsibility". If instead the pattern
2147 </p>
2148 <pre class="programlisting">
2149 (sens|respons)e and (?1)ibility
2150 </pre>
2151 <p>
2152 is used, it does match "sense and responsibility" as well as the other
2153 two strings. Another example is given in the discussion of DEFINE above.
2154 </p>
2155 <p>
2156 Like recursive subpatterns, a "subroutine" call is always treated as an atomic
2157 group. That is, once it has matched some of the string, it is never
2158 re-entered, even if it contains untried alternatives and there is a subsequent
2159 matching failure.
2160 </p>
2161 <p>
2162 When a subpattern is used as a subroutine, processing options such as
2163 case-independence are fixed when the subpattern is defined. They cannot be
2164 changed for different calls. For example, consider this pattern:
2165 </p>
2166 <pre class="programlisting">
2167 (abc)(?i:(?1))
2168 </pre>
2169 <p>
2170 It matches "abcabc". It does not match "abcABC" because the change of
2171 processing option does not affect the called subpattern.
2172 </p>
2173 </div>
2174 <div class="refsect1">
2175 <a name="id728791"></a><h2>Copyright</h2>
2176 <p>
2177 This document was copied and adapted from the PCRE documentation,
2178 specifically from the man page for pcrepattern.
2179 The original copyright note is:
2180 </p>
2181 <pre class="programlisting">
2182 Copyright (c) 1997-2006 University of Cambridge.
2183
2184 Redistribution and use in source and binary forms, with or without
2185 modification, are permitted provided that the following conditions are met:
2186
2187     * Redistributions of source code must retain the above copyright notice,
2188       this list of conditions and the following disclaimer.
2189
2190     * Redistributions in binary form must reproduce the above copyright
2191       notice, this list of conditions and the following disclaimer in the
2192       documentation and/or other materials provided with the distribution.
2193
2194     * Neither the name of the University of Cambridge nor the name of Google
2195       Inc. nor the names of their contributors may be used to endorse or
2196       promote products derived from this software without specific prior
2197       written permission.
2198
2199 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
2200 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2201 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2202 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
2203 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2204 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2205 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2206 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2207 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2208 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2209 POSSIBILITY OF SUCH DAMAGE.
2210 </pre>
2211 </div>
2212 </div>
2213 <div class="footer">
2214 <hr>
2215           Generated by GTK-Doc V1.18</div>
2216 </body>
2217 </html>