-
Notifications
You must be signed in to change notification settings - Fork 292
/
regexes.pod6
2413 lines (1783 loc) · 83 KB
/
regexes.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=begin pod :tag<perl6>
=TITLE Regexes
=SUBTITLE Pattern matching against strings
X<|Regular Expressions>
Regular expressions, I<regexes> for short, are a sequence of characters that
describe a pattern of text. Pattern matching is the process of matching
those patterns to actual text.
=head1 X<Lexical conventions|quote,/ /;quote,rx;quote,m>
Perl 6 has special syntax for writing regexes:
m/abc/; # a regex that is immediately matched against $_
rx/abc/; # a Regex object; allow adverbs to be used before regex
/abc/; # a Regex object; shorthand version of 'rx/ /' operator
For the first two examples, delimiters other than the slash can be used:
m{abc};
rx{abc};
Note that neither the colon nor round parentheses can be delimiters; the colon
is forbidden because it clashes with adverbs, such as C<rx:i/abc/>
(case insensitive regexes), and round parentheses indicate a function call
instead.
Example of difference between C<m/ /> and C</ /> operators:
my $match;
$_ = "abc";
$match = m/.+/; say $match; say $match.^name; # OUTPUT: «「abc」Match»
$match = /.+/; say $match; say $match.^name; # OUTPUT: «/.+/Regex»
Whitespace in regexes is generally ignored (except with the C<:s> or,
completely, C<:sigspace> adverb).
Comments work within a regular expression:
/ word #`(match lexical "word") /
=head1 Literals
The simplest case for a regex is a match against a string literal:
if 'properly' ~~ / perl / {
say "'properly' contains 'perl'";
}
Alphanumeric characters and the underscore C<_> are matched literally. All
other characters must either be escaped with a backslash (for example, C<\:>
to match a colon), or be within quotes:
/ 'two words' /; # matches 'two words' including the blank
/ "a:b" /; # matches 'a:b' including the colon
/ '#' /; # matches a hash character
Strings are searched left to right, so it is enough if only part of the string
matches the regex:
if 'Life, the Universe and Everything' ~~ / and / {
say ~$/; # OUTPUT: «and»
say $/.prematch; # OUTPUT: «Life, the Universe »
say $/.postmatch; # OUTPUT: « Everything»
say $/.from; # OUTPUT: «19»
say $/.to; # OUTPUT: «22»
};
Match results are stored in the C<$/> variable and are also returned from
the match. The result is of type L<Match|/type/Match> if the match was
successful; otherwise it is L<Nil|/type/Nil>.
=head1 X<Wildcards|regex, .>
An unescaped dot C<.> in a regex matches any single character.
So, these all match:
'perl' ~~ /per./; # matches the whole string
'perl' ~~ / per . /; # the same; whitespace is ignored
'perl' ~~ / pe.l /; # the . matches the r
'speller' ~~ / pe.l/; # the . matches the first l
This doesn't match:
'perl' ~~ /. per /;
because there's no character to match before C<per> in the target string.
Note that C<.> now does match B<any> single character, that is, it matches
C<\n>. So the text below match:
my $text = qq:to/END/
Although I am a
multi-line text,
now can be matched
with /.*/.
END
;
say $text ~~ / .* /;
# OUTPUT «「Although I am amulti-line text,now can be matchedwith /.*/」»
=head1 Character classes
=head2 Backslashed character classes
There are predefined character classes of the form C<\w>. Its negation is
written with an upper-case letter, C<\W>.
=item X<C<\n> and C<\N>|regex,\n;regex,\N>
C<\n> matches a single, logical newline character.C<\N> matches a single
character that's not a logical newline.
What is considered as a single newline character is defined via the compile
time variable L«C<$?NL>|/language/variables#index-entry-$?NL», and the
L<newline pragma|/language/pragmas>.
Therefore, C<\n> is supposed to be able to match either a Unix-like
newline C<"\n">, a Microsoft Windows style one C<"\r\n">, or one in the Mac style C<"\r">.
=item X<C<\t> and C<\T>|regex,\t;regex,\T>
C<\t> matches a single tab/tabulation character, C<U+0009>. C<\T> matches a
single character that is not a tab.
Note that exotic tabs like the C<U+000B VERTICAL TABULATION> character are not
included here.
=item X<C<\h> and C<\H>|regex,\h;regex,\H>
C<\h> matches a single horizontal whitespace character. C<\H> matches a
single character that is not a horizontal whitespace character.
Examples for horizontal whitespace characters are
=begin code :lang<text>
U+0020 SPACE
U+00A0 NO-BREAK SPACE
U+0009 CHARACTER TABULATION
U+2001 EM QUAD
=end code
Vertical whitespace like newline characters are explicitly excluded; those
can be matched with C<\v>, and C<\s> matches any kind of whitespace.
=item X<C<\v> and C<\V>|regex,\v;regex,\V>
C<\v> matches a single vertical whitespace character. C<\V> matches a single
character that is not vertical whitespace.
Examples for vertical whitespace characters:
=begin code :lang<text>
U+000A LINE FEED
U+000B VERTICAL TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE
U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR
=end code
Use C<\s> to match any kind of whitespace, not just vertical whitespace.
=item X<C<\s> and C<\S>|regex,\s;regex,\S>
C<\s> matches a single whitespace character. C<\S> matches a single
character that is not whitespace.
say $/.prematch if 'Match the first word.' ~~ / \s+ /;
# OUTPUT: «Match»
=item X<C<\d> and C<\D>|regex,\d;regex,\D>
C<\d> matches a single digit (Unicode property C<N>) and C<\D> matches a
single character that is not a digit.
'ab42' ~~ /\d/ and say ~$/; # OUTPUT: «4»
'ab42' ~~ /\D/ and say ~$/; # OUTPUT: «a»
Note that not only the Arabic digits (commonly used in the Latin
alphabet) match C<\d>, but also digits from other scripts.
Examples for digits are:
=begin code :lang<text>
U+0035 5 DIGIT FIVE
U+0BEB ௫ TAMIL DIGIT FIVE
U+0E53 ๓ THAI DIGIT THREE
U+17E5 ៥ KHMER DIGIT FIVE
=end code
=item X<C<\w> and C<\W>|regex,\w;regex,\W>
C<\w> matches a single word character, i.e. a letter (Unicode category
L), a digit or an underscore. C<\W> matches a single character that is
not a word character.
Examples of word characters:
=begin code :lang<text>
0041 A LATIN CAPITAL LETTER A
0031 1 DIGIT ONE
03B4 δ GREEK SMALL LETTER DELTA
03F3 ϳ GREEK LETTER YOT
0409 Љ CYRILLIC CAPITAL LETTER LJE
=end code
=head2 Predefined character classes
=begin table
Class | Shorthand | Description
=========+===========+=============
<alpha> | | Alphabetic characters including _
<digit> | \d | Decimal digits
<xdigit> | | Hexadecimal digit [0-9A-Fa-f]
<alnum> | \w | <alpha> plus <digit>
<punct> | | Punctuation and Symbols (only Punct beyond ASCII)
<graph> | | <alnum> plus <punct>
<space> | \s | Whitespace
<cntrl> | | Control characters
<print> | | <graph> plus <space>, but no <cntrl>
<blank> | \h | Horizontal whitespace
<lower> | <:Ll> | Lowercase characters
<upper> | <:Lu> | Uppercase characters
<same> | | Matches between two identical characters
<wb> | | Word Boundary
<ws> | | Whitespace. This is actually a default rule.
<ww> | | Within Word
<ident> | | Identifier. Also a default rule.
=end table
Note that the character classes C«<same>», C«<wb>» and C«<ww>» are
so called zero-width assertions, which do not really match a
character.
=head2 X«Unicode properties|regex,<:property>»
The character classes mentioned so far are mostly for convenience; another
approach is to use Unicode character properties. These come in the form
C«<:property>», where C<property> can be a short or long Unicode General
Category name. These use pair syntax.
To match against a Unicode property you can use either smartmatch or
L<C<uniprop>|/routine/uniprop>:
"a".uniprop('Script'); # OUTPUT: «Latin»
"a" ~~ / <:Script<Latin>> /; # OUTPUT: «「a」»
"a".uniprop('Block'); # OUTPUT: «Basic Latin»
"a" ~~ / <:Block('Basic Latin')> /; # OUTPUT: «「a」»
These are the unicode general categories used for matching:
=begin table
Short | Long
========+========
L | Letter
LC | Cased_Letter
Lu | Uppercase_Letter
Ll | Lowercase_Letter
Lt | Titlecase_Letter
Lm | Modifier_Letter
Lo | Other_Letter
M | Mark
Mn | Nonspacing_Mark
Mc | Spacing_Mark
Me | Enclosing_Mark
N | Number
Nd | Decimal_Number or digit
Nl | Letter_Number
No | Other_Number
P | Punctuation or punct
Pc | Connector_Punctuation
Pd | Dash_Punctuation
Ps | Open_Punctuation
Pe | Close_Punctuation
Pi | Initial_Punctuation
Pf | Final_Punctuation
Po | Other_Punctuation
S | Symbol
Sm | Math_Symbol
Sc | Currency_Symbol
Sk | Modifier_Symbol
So | Other_Symbol
Z | Separator
Zs | Space_Separator
Zl | Line_Separator
Zp | Paragraph_Separator
C | Other
Cc | Control or cntrl
Cf | Format
Cs | Surrogate
Co | Private_Use
Cn | Unassigned
=end table
For example, C«<:Lu>» matches a single, upper-case letter.
Its negation is this: C«<:!property>». So, C«<:!Lu>» matches a single
character that is not an upper-case letter.
Categories can be used together, with an infix operator:
=begin table
Operator | Meaning
==========+=========
+ | set union
- | set difference
=end table
To match either a lower-case letter or a number, write
C«<:Ll+:N>» or C«<:Ll+:Number>» or C«<+ :Lowercase_Letter + :Number>».
It's also possible to group categories and sets of categories with
parentheses; for example:
say $0 if 'perl6' ~~ /\w+(<:Ll+:N>)/ # OUTPUT: «「6」»
=head2 X«Enumerated character classes and ranges|regex,<[ ]>;regex,<-[ ]>»
Sometimes the pre-existing wildcards and character classes are not
enough. Fortunately, defining your own is fairly simple. Within C«<[ ]>»,
you can put any number of single characters and ranges of characters
(expressed with two dots between the end points), with or without
whitespace.
"abacabadabacaba" ~~ / <[ a .. c 1 2 3 ]>* /;
# Unicode hex codepoint range
"ÀÁÂÃÄÅÆ" ~~ / <[ \x[00C0] .. \x[00C6] ]>* /;
# Unicode named codepoint range
"αβγ" ~~ /<[\c[GREEK SMALL LETTER ALPHA]..\c[GREEK SMALL LETTER GAMMA]]>*/;
Within the C«< >» you can use C<+> and C<-> to add or remove multiple range
definitions and even mix in some of the unicode categories above. You can also
write the backslashed forms for character classes between the C<[ ]>.
/ <[\d] - [13579]> /;
# starts with \d and removes odd ASCII digits, but not quite the same as
/ <[02468]> /;
# because the first one also contains "weird" unicodey digits
You can include Unicode properties in the list as well:
/<:Zs + [\x9] - [\xA0]>/
# Any character with "Zs" property, or a tab, but not a newline
You can use C<\> to escape characters that would have some meaning in the
regular expression:
say "[ hey ]" ~~ /<-[ \] \[ \s ]>+/; # OUTPUT: «「hey」»
To negate a character class, put a C<-> after the opening angle:
say 'no quotes' ~~ / <-[ " ]> + /; # matches characters except "
A common pattern for parsing quote-delimited strings involves negated
character classes:
say '"in quotes"' ~~ / '"' <-[ " ]> * '"'/;
This first matches a quote, then any characters that aren't quotes, and then
a quote again. The meaning of C<*> and C<+> in the examples above are
explained in the next section, Quantifier.
Just as you can use the C<-> for both set difference and negation of a
single value, you can also explicitly put a C<+> in front:
/ <+[123]> / # same as <[123]>
=head1 Quantifiers
A quantifier makes the preceding atom match a
variable number of times. For example, C<a+> matches one or more C<a>
characters.
Quantifiers bind tighter than concatenation, so C<ab+> matches one C<a>
followed by one or more C<b>s. This is different for quotes, so C<'ab'+>
matches the strings C<ab>, C<abab>, C<ababab> etc.
=head2 X<One or more: C<+>|regex quantifier,+>
The C<+> quantifier makes the preceding atom match one or more times, with
no upper limit.
For example, to match strings of the form C<key=value>, you can write a regex
like this:
/ \w+ '=' \w+ /
=head2 X<Zero or more: C<*>|regex quantifier,*>
The C<*> quantifier makes the preceding atom match zero or more times, with
no upper limit.
For example, to allow optional whitespace between C<a> and C<b> you can write
/ a \s* b /
=head2 X<Zero or one: C<?>|regex quantifier,?>
The C<?> quantifier makes the preceding atom match zero or once.
From example, to match C<dog> or C<dogs>, you can write:
/ dogs? /
=head2 X<General quantifier: C<** min..max>|regex quantifier,**>
To quantify an atom an arbitrary number of times, use C<**> quantifier.
The quantifier takes a single L<Int> or a L<Range> on the right-hand side
that specifies the number of times to match. If L<Range> is specified,
the end-points specify the minimum and maximum number of times to match.
=begin code
say 'abcdefg' ~~ /\w ** 4/; # OUTPUT: «「abcd」»
say 'a' ~~ /\w ** 2..5/; # OUTPUT: «Nil»
say 'abc' ~~ /\w ** 2..5/; # OUTPUT: «「abc」»
say 'abcdefg' ~~ /\w ** 2..5/; # OUTPUT: «「abcde」»
say 'abcdefg' ~~ /\w ** 2^..^5/; # OUTPUT: «「abcd」»
say 'abcdefg' ~~ /\w ** ^3/; # OUTPUT: «「ab」»
say 'abcdefg' ~~ /\w ** 1..*/; # OUTPUT: «「abcdefg」»
=end code
Only basic literal syntax for the right-hand side of the quantifier
is supported, to avoid ambiguities with other regex constructs. If you need
to use a more complex expression; for example, a L<Range> made from
variables—enclose the L<Range> into curly braces:
=begin code
my $start = 3;
say 'abcdefg' ~~ /\w ** {$start .. $start+2}/; # OUTPUT: «「abcde」»
say 'abcdefg' ~~ /\w ** {π.Int}/; # OUTPUT: «「abc」»
=end code
Negative values are treated like zero:
=begin code
say 'abcdefg' ~~ /\w ** {-Inf}/; # OUTPUT: «「」»
say 'abcdefg' ~~ /\w ** {-42}/; # OUTPUT: «「」»
say 'abcdefg' ~~ /\w ** {-10..-42}/; # OUTPUT: «「」»
say 'abcdefg' ~~ /\w ** {-42..-10}/; # OUTPUT: «「」»
=end code
If then, the resultant value is C<Inf>
or C<NaN> or the resultant L<Range> is empty, non-Numeric, contains C<NaN>
end-points, or has minimum effective end-point as C<Inf>, the
C<X::Syntax::Regex::QuantifierValue> exception will be thrown:
=begin code
(try say 'abcdefg' ~~ /\w ** {42..10}/ )
orelse say ($!.^name, $!.empty-range);
# OUTPUT: «(X::Syntax::Regex::QuantifierValue True)»
(try say 'abcdefg' ~~ /\w ** {Inf..Inf}/)
orelse say ($!.^name, $!.inf);
# OUTPUT: «(X::Syntax::Regex::QuantifierValue True)»
(try say 'abcdefg' ~~ /\w ** {NaN..42}/ )
orelse say ($!.^name, $!.non-numeric-range);
# OUTPUT: «(X::Syntax::Regex::QuantifierValue True)»
(try say 'abcdefg' ~~ /\w ** {"a".."c"}/)
orelse say ($!.^name, $!.non-numeric-range);
# OUTPUT: «(X::Syntax::Regex::QuantifierValue True)»
(try say 'abcdefg' ~~ /\w ** {Inf}/)
orelse say ($!.^name, $!.inf);
# OUTPUT: «(X::Syntax::Regex::QuantifierValue True)»
(try say 'abcdefg' ~~ /\w ** {NaN}/)
orelse say ($!.^name, $!.non-numeric);
# OUTPUT: «(X::Syntax::Regex::QuantifierValue True)»
=end code
=head2 X<Modified quantifier: C<%>, C<%%>|regex,%;regex,%%>
To more easily match things like comma separated values, you can tack on a
C<%> modifier to any of the above quantifiers to specify a separator that must
occur between each of the matches. For example, C<a+ % ','> will match
C<a> or C<a,a> or C<a,a,a>, etc. To also match trailing delimiters
( C<a,> or C<a,a,> ), you can use C<%%> instead of C<%>.
The quantifier interacts with C<%> and controls the number of overall
repetitions that can match successfully, so C<a* % ','> also matches the empty
string. If you want match words delimited by commas, you might need to nest an
ordinary and a modified quantifier:
=begin code
say so 'abc,def' ~~ / ^ [\w+] ** 1 % ',' $ /; # Output: «False»
say so 'abc,def' ~~ / ^ [\w+] ** 2 % ',' $ /; # Output: «True»
=end code
=head2 X<Preventing backtracking: C<:>|regex,:>
You can prevent backtracking in regexes by attaching a C<:> modifier
to the quantifier:
=begin code
my $str = "ACG GCT ACT An interesting chain";
say $str ~~ /<[ACGT\s]>+ \s+ (<[A..Z a..z \s]>+)/;
# OUTPUT: «「ACG GCT ACT An interesting chain」 0 => 「An interesting chain」»
say $str ~~ /<[ACGT\s]>+: \s+ (<[A..Z a..z \s]>+)/;
# OUTPUT: «Nil»
=end code
In the second case, the C<A> in C<An> had already been "absorbed" by the
pattern, preventing the matching of the second part of the pattern, after
C<\s+>. Generally we will want the opposite: prevent backtracking to match
precisely what we are looking for.
In most cases, you will want to prevent backtracking for efficiency reasons, for
instance here:
=for code :preamble<my $str>
say $str ~~ m:g/[(<[ACGT]> **: 3) \s*]+ \s+ (<[A..Z a..z \s]>+)/;
# OUTPUT:
# (「ACG GCT ACT An interesting chain」
# 0 => 「ACG」
# 0 => 「GCT」
# 0 => 「ACT」
# 1 => 「An interesting chain」)
Although in this case, eliminating the C<:> from behind C<**> would make it behave exactly in the same way. The best use is to create I<tokens> that will not be backtracked:
$_ = "ACG GCT ACT IDAQT";
say m:g/[(\w+:) \s*]+ (\w+) $$/;
# OUTPUT:
# (「ACG GCT ACT IDAQT」
# 0 => 「ACG」
# 0 => 「GCT」
# 0 => 「ACT」
# 1 => 「IDAQT」)
Without the C<:> following C<\w+>, the I<ID> part captured would have been
simply C<T>, since the pattern would go ahead and match everything, leaving a
single letter to match the C<\w+> expression at the end of tne line.
=head2 X<Greedy versus frugal quantifiers: C<?>|regex,?>
By default, quantifiers request a greedy match:
=begin code
'abababa' ~~ /a .* a/ && say ~$/; # OUTPUT: «abababa»
=end code
You can attach a C<?> modifier to the quantifier to enable frugal
matching:
=begin code
'abababa' ~~ /a .*? a/ && say ~$/; # OUTPUT: «aba»
=end code
You can also enable frugal matching for general quantifiers:
say '/foo/o/bar/' ~~ /\/.**?{1..10}\//; # OUTPUT: «「/foo/」»
say '/foo/o/bar/' ~~ /\/.**!{1..10}\//; # OUTPUT: «「/foo/o/bar/」»
Greedy matching can be explicitly requested with the C<!> modifier.
=head1 X<Alternation: C<||>|regex,||>
To match one of several possible alternatives, separate them by C<||>; the
first matching alternative wins.
For example, C<ini> files have the following form:
=begin code :lang<text>
[section]
key = value
=end code
Hence, if you parse a single line of an C<ini> file, it can be either a
section or a key-value pair and the regex would be (to a first
approximation):
/ '[' \w+ ']' || \S+ \s* '=' \s* \S* /
That is, either a word surrounded by square brackets, or a string of
non-whitespace characters, followed by zero or more spaces, followed by the
equals sign C<=>, followed again by optional whitespace, followed by another
string of non-whitespace characters.
Even in non-backtracking contexts, the alternation operator C<||> tries
all the branches in order until the first one matches.
=head1 X<Longest alternation: C<|>|regex,|>
In short, in regex branches separated by C<|>, the longest token match wins,
independent of the textual ordering in the regex. However, what C<|> really
does is more than that.
It does not decide which branch wins after finishing the whole match,
but follows the L<longest-token matching (LTM) strategy|https://design.perl6.org/S05.html#Longest-token_matching>.
Briefly, what C<|> does is this:
=item1 First, select the branch which has the longest declarative prefix.
say "abc" ~~ /ab | a.* /; # Output: ⌜abc⌟
say "abc" ~~ /ab | a {} .* /; # Output: ⌜ab⌟
say "if else" ~~ / if | if <.ws> else /; # Output: 「if」
say "if else" ~~ / if | if \s+ else /; # Output: 「if else」
As is shown above, C<a.*> is a declarative prefix, while C<a {} .*> terminates
at C<{}>, then its declarative prefix is C<a>. Note that non-declarative atoms
terminate declarative prefix. This is quite important if you want to apply
C<|> in a C<rule>, which automatically enables C<:s>, and C«<.ws>» accidentally
terminates declarative prefix.
=item1 If it's a tie, select the match with the highest specificity.
say "abc" ~~ /a. | ab { print "win" } /; # Output: win「ab」
When two alternatives match at the same length, the tie is broken by
specificity. That is, C<ab>, as an exact match, counts as closer than C<a.>,
which uses character classes.
=item1 If it's still a tie, use additional tie-breakers.
say "abc" ~~ /a\w| a. { print "lose" } /; # Output: ⌜ab⌟
If the tie breaker above doesn't work, then the textually earlier alternative
takes precedence.
For more details, see
L<the LTM strategy|https://design.perl6.org/S05.html#Longest-token_matching>.
=head2 Quoted lists are LTM matches
Using a quoted list in a regex is equivalent to specifying the
longest-match alternation of the list's elements. So, the following
match:
say 'food' ~~ /< f fo foo food >/; # OUTPUT: «「food」»
is equivalent to:
say 'food' ~~ / f | fo | foo | food /; # OUTPUT: «「food」»
Note that the space after the first C«<» is significant here: C«<food>»
calls the named rule C<food> while C«< food >» and C«< food>» specify
quoted lists with a single element, C<'food'>.
Arrays can also be interpolated into a regex to achieve the same effect:
my @increasingly-edible = <f fo foo food>;
say 'food' ~~ /@increasingly-edible/; # OUTPUT: «「food」»
This is documented further under L<Regex Interpolation|#Regex_interpolation>,
below.
=head1 X<Conjunction: C<&&>|regex,&&>
Matches successfully if all C<&&>-delimited segments match the same substring
of the target string. The segments are evaluated left to right.
This can be useful for augmenting an existing regex. For example if you have
a regex C<quoted> that matches a quoted string, then C</ <quoted> && <-[x]>* />
matches a quoted string that does not contain the character C<x>.
Note that you cannot easily obtain the same behavior with a lookahead, that
is, a regex doesn't consume characters, because a lookahead doesn't stop
looking when the quoted string stops matching.
=begin code
say 'abc' ~~ / <?before a> && . /; # OUTPUT: «Nil»
say 'abc' ~~ / <?before a> . && . /; # OUTPUT: «「a」»
say 'abc' ~~ / <?before a> . /; # OUTPUT: «「a」»
say 'abc' ~~ / <?before a> .. /; # OUTPUT: «「ab」»
=end code
=head1 X<Conjunction: C<&>|regex,&>
Much like C<&&> in a regex, it matches successfully if all segments
separated by C<&> match the same part of the target string.
C<&> (unlike C<&&>) is considered declarative, and notionally all the
segments can be evaluated in parallel, or in any order the compiler chooses.
=head1 Anchors
Regexes search an entire string for matches. Sometimes this is not what
you want. Anchors match only at certain positions in the string, thereby
anchoring the regex match to that position.
=head2 X<Start of string and end of string|regex,^;regex,$>
The C<^> anchor only matches at the start of the string:
say so 'properly' ~~ / perl/; # OUTPUT: «True»
say so 'properly' ~~ /^ perl/; # OUTPUT: «False»
say so 'perly' ~~ /^ perl/; # OUTPUT: «True»
say so 'perl' ~~ /^ perl/; # OUTPUT: «True»
The C<$> anchor only matches at the end of the string:
say so 'use perl' ~~ / perl /; # OUTPUT: «True»
say so 'use perl' ~~ / perl $/; # OUTPUT: «True»
say so 'perly' ~~ / perl $/; # OUTPUT: «False»
You can combine both anchors:
say so 'use perl' ~~ /^ perl $/; # OUTPUT: «False»
say so 'perl' ~~ /^ perl $/; # OUTPUT: «True»
Keep in mind that C<^> matches the start of a B<string>, not the start of
a B<line>. Likewise, C<$> matches the end of a B<string>, not the end of
a B<line>.
The following is a multi-line string:
my $str = chomp q:to/EOS/;
Keep it secret
and keep it safe
EOS
# 'safe' is at the end of the string
say so $str ~~ /safe $/; # OUTPUT: «True»
# 'secret' is at the end of a line, not the string
say so $str ~~ /secret $/; # OUTPUT: «False»
# 'Keep' is at the start of the string
say so $str ~~ /^Keep /; # OUTPUT: «True»
# 'and' is at the start of a line -- not the string
say so $str ~~ /^and /; # OUTPUT: «False»
=head2 X<Start of line and end of line|regex,^^;regex,$$>
The C<^^> anchor matches at the start of a logical line. That is, either
at the start of the string, or after a newline character. However, it does not
match at the end of the string, even if it ends with a newline character.
The C<$$> anchor matches at the end of a logical line. That is, before a newline
character, or at the end of the string when the last character is not a
newline character.
To understand the following example, it's important to know that the
C<q:to/EOS/...EOS> L<heredoc|/language/quoting#Heredocs:_:to> syntax removes
leading indention to the same level as the C<EOS> marker, so that the first,
second and last lines have no leading space and the third and fourth lines have
two leading spaces each.
my $str = q:to/EOS/;
There was a young man of Japan
Whose limericks never would scan.
When asked why this was,
He replied "It's because I always try to fit
as many syllables into the last line as ever I possibly can."
EOS
# 'There' is at the start of string
say so $str ~~ /^^ There/; # OUTPUT: «True»
# 'limericks' is not at the start of a line
say so $str ~~ /^^ limericks/; # OUTPUT: «False»
# 'as' is at start of the last line
say so $str ~~ /^^ as/; # OUTPUT: «True»
# there are blanks between start of line and the "When"
say so $str ~~ /^^ When/; # OUTPUT: «False»
# 'Japan' is at end of first line
say so $str ~~ / Japan $$/; # OUTPUT: «True»
# there's a . between "scan" and the end of line
say so $str ~~ / scan $$/; # OUTPUT: «False»
# matched at the last line
say so $str ~~ / '."' $$/; # OUTPUT: «True»
=head2 X«Word boundary|regex, <|w>;regex, <!|w>»
To match any word boundary, use C«<|w>» or C«<?wb>». This is similar to
X«C<\b>|regex deprecated,\b» of other languages.
To match not a word boundary, use C«<!|w>» or C«<!wb>». This is similar to
X«C<\B>|regex deprecated,\B» of other languages.
These are both zero-width regex elements.
say "two-words" ~~ / two<|w>\-<|w>words /; # OUTPUT: «「two-words」»
say "twowords" ~~ / two<!|w><!|w>words /; # OUTPUT: «「twowords」»
X<<<|regex, <<; regex, >>; regex, «; regex, »>>>
=head2 Left and right word boundary
C«<<» matches a left word boundary. It matches positions where there is a
non-word character at the left, or the start of the string, and a word
character to the right.
C«>>» matches a right word boundary. It matches positions where there
is a word character at the left and a non-word character at the right, or
the end of the string.
These are both zero-width regex elements.
my $str = 'The quick brown fox';
say so ' ' ~~ /\W/; # OUTPUT: «True»
say so $str ~~ /br/; # OUTPUT: «True»
say so $str ~~ /<< br/; # OUTPUT: «True»
say so $str ~~ /br >>/; # OUTPUT: «False»
say so $str ~~ /own/; # OUTPUT: «True»
say so $str ~~ /<< own/; # OUTPUT: «False»
say so $str ~~ /own >>/; # OUTPUT: «True»
say so $str ~~ /<< The/; # OUTPUT: «True»
say so $str ~~ /fox >>/; # OUTPUT: «True»
You can also use the variants C<«> and C<»> :
my $str = 'The quick brown fox';
say so $str ~~ /« own/; # OUTPUT: «False»
say so $str ~~ /own »/; # OUTPUT: «True»
To see the difference between C«<|w>» and C<«>, C<»>:
say "stuff here!!!".subst(:g, />>/, '|'); # OUTPUT: «stuff| here|!!!»
say "stuff here!!!".subst(:g, /<</, '|'); # OUTPUT: «|stuff |here!!!»
say "stuff here!!!".subst(:g, /<|w>/, '|'); # OUTPUT: «|stuff| |here|!!!»
=head2 Summary of anchors
Anchors are zero-width regex elements. Hence they do not use up a character of
the input string, that is, they do not advance the current position at which
the regex engine tries to match. A good mental model is that they match between
two characters of an input string, or before the first, or after the last
character of an input string.
=begin table
Anchor | Description | Examples
========+=====================+=================
^ | Start of string | "⏏two\nlines"
^^ | Start of line | "⏏two\n⏏lines"
$ | End of string | "two\nlines⏏"
$$ | End of line | "two⏏\nlines⏏"
<< or « | Left word boundary | "⏏two ⏏words"
>> or » | Right word boundary | "two⏏ words⏏"
<?wb> | Any word boundary | "⏏two⏏ ⏏words⏏~!"
<!wb> | Not a word boundary | "t⏏w⏏o w⏏o⏏r⏏d⏏s~⏏!"
<?ww> | Within word | "t⏏w⏏o w⏏o⏏r⏏d⏏s~!"
<!ww> | Not within word | "⏏two⏏ ⏏words⏏~⏏!⏏"
=end table
=head1 Zero-width assertions
Zero-Width Assertions can help you implement your own anchor.
A zero-width assertion turns another regex into an anchor, making
them consume no characters of the input string. There are two variants:
lookahead and lookbehind assertions.
Technically, anchors are also zero-width assertions, and they can look
both ahead and behind.
=head2 X<Lookahead assertions|regex,before>
To check that a pattern appears before another pattern, use a
lookahead assertion via the C<before> assertion. This has the form:
<?before pattern>
Thus, to search for the string C<foo> which is immediately followed by the
string C<bar>, use the following regexp:
/ foo <?before bar> /
For example:
say "foobar" ~~ / foo <?before bar> /; # OUTPUT: «foo»
However, if you want to search for a pattern which is B<not> immediately
followed by some pattern, then you need to use a negative lookahead
assertion, this has the form:
<!before pattern>
In the following example, all occurrences of C<foo> which is not before
C<bar> would match with
say "foobaz" ~~ / foo <!before bar> /; # OUTPUT: «foo»
Lookahead assertions can be used also with other patterns, like
characters ranges, interpolated variables, subscripts and so on. In such
cases it does suffice to use a C<?>, or a C<!> for the negate form.
For instance, the following lines all produce the very same result:
say 'abcdefg' ~~ rx{ abc <?before def> }; # OUTPUT: 「abc」
say 'abcdefg' ~~ rx{ abc <?[ d..f ]> }; # OUTPUT: 「abc」
my @ending_letters = <d e f>;
say 'abcdefg' ~~ rx{ abc <?@ending_letters> }; # OUTPUT: 「abc」
A practical use of lookahead assertions is in substitutions, where
you only want to substitute regex matches that are in a certain
context. For example, you might want to substitute only numbers
that are followed by a unit (like I<kg>), but not other numbers:
my @units = <kg m km mm s h>;
$_ = "Please buy 2 packs of sugar, 1 kg each";
s:g[\d+ <?before \s* @units>] = 5 * $/;
say $_; # OUTPUT: Please buy 2 packs of sugar, 5 kg each
Since the lookahead is not part of the match object, the unit
is not substituted.
=head2 X<Lookbehind assertions|regex,after>
To check that a pattern appears after another pattern, use a
lookbehind assertion via the C<after> assertion. This has the form:
<?after pattern>
Therefore, to search for the string C<bar> immediately preceded by the
string C<foo>, use the following regexp:
/ <?after foo> bar /
For example:
say "foobar" ~~ / <?after foo> bar /; # OUTPUT: «bar»
However, if you want to search for a pattern which is B<not> immediately
preceded by some pattern, then you need to use a negative lookbehind
assertion, this has the form:
<!after pattern>
Hence all occurrences of C<bar> which do not have C<foo> before them
would be matched by
say "fotbar" ~~ / <!after foo> bar /; # OUTPUT: «bar»
These are, as in the case of lookahead, zero-width assertions which do not I<consume> characters, like here:
say "atfoobar" ~~ / (.**3) .**2 <?after foo> bar /;
# OUTPUT: «「atfoobar」 0 => 「atf」»
where we capture the first 3 of the 5 characters before bar, but only if C<bar>
is preceded by C<foo>. The fact that the assertion is zero-width allows us to
use part of the characters in the assertion for capture.
=head1 Grouping and capturing
In regular (non-regex) Perl 6, you can use parentheses to group things
together, usually to override operator precedence:
say 1 + 4 * 2; # OUTPUT: «9», parsed as 1 + (4 * 2)
say (1 + 4) * 2; # OUTPUT: «10»
The same grouping facility is available in regexes:
/ a || b c /; # matches 'a' or 'bc'
/ ( a || b ) c /; # matches 'ac' or 'bc'
The same grouping applies to quantifiers:
/ a b+ /; # matches an 'a' followed by one or more 'b's
/ (a b)+ /; # matches one or more sequences of 'ab'
/ (a || b)+ /; # matches a string of 'a's and 'b's, except empty string
An unquantified capture produces a L<Match> object. When a capture is
quantified (except with the C<?> quantifier) the capture becomes a list of
L<Match> objects instead.
=head2 X«Capturing|regex,( )»
The round parentheses don't just group, they also I<capture>; that is, they
make the string matched within the group available as a variable, and also as
an element of the resulting L<Match> object:
my $str = 'number 42';
if $str ~~ /'number ' (\d+) / {
say "The number is $0"; # OUTPUT: The number is 42
# or
say "The number is $/[0]"; # OUTPUT: The number is 42
}
Pairs of parentheses are numbered left to right, starting from zero.
if 'abc' ~~ /(a) b (c)/ {
say "0: $0; 1: $1"; # OUTPUT: «0: a; 1: c»
}
The C<$0> and C<$1> etc. syntax is shorthand. These captures
are canonically available from the match object C<$/> by using it as a list,
so C<$0> is actually syntactic sugar for C<$/[0]>.
Coercing the match object to a list gives an easy way to programmatically
access all elements: