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