/
S05-regex.pod
4636 lines (3180 loc) · 150 KB
/
S05-regex.pod
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
=encoding utf8
=head1 TITLE
Synopsis 5: Regexes and Rules
=head1 AUTHORS
Damian Conway <damian@conway.org>
Allison Randal <al@shadowed.net>
Patrick Michaud <pmichaud@pobox.com>
Larry Wall <larry@wall.org>
Moritz Lenz <moritz@faui2k3.org>
=head1 VERSION
Created: 24 Jun 2002
Last Modified: 31 Jul 2012
Version: 158
This document summarizes Apocalypse 5, which is about the new regex
syntax. We now try to call them I<regex> rather than "regular
expressions" because they haven't been regular expressions for a
long time, and we think the popular term "regex" is in the process of
becoming a technical term with a precise meaning of: "something you do
pattern matching with, kinda like a regular expression". On the other
hand, one of the purposes of the redesign is to make portions of
our patterns more amenable to analysis under traditional regular
expression and parser semantics, and that involves making careful
distinctions between which parts of our patterns and grammars are
to be treated as declarative, and which parts as procedural.
In any case, when referring to recursive patterns within a grammar,
the terms I<rule> and I<token> are generally preferred over I<regex>.
=head1 Overview
In essence, Perl 6 natively implements Parsing Expression Grammars (PEGs)
as an extension of regular expression notation. PEGs require that you
provide a "pecking order" for ambiguous parses. Perl 6's pecking order
is determined by a multi-level tie-breaking test:
1) Longest token matching: food\s+ beats foo by 2 or more positions
2) Longest literal prefix: food\w* beats foo\w* by 1 position
3) Declaration from most-derived grammar beats less-derived
4) Within a given compilation unit, earlier declaration wins
5) Declaration with least number of 'uses' wins
Note that tiebreaker #5 can occur only when a grammar is monkey-patched
from another compilation unit. Like #3, it privileges local declarations
over distant ones.
In addition to this pecking order, if any rule chosen under the pecking
backtracks, the next best rule is chosen. That is, the pecking order
determines a candidate list; just because one candidate is chosen does not
mean the rest are thrown away. They may, however, be explicitly thrown away
by an appropriate backtracking control (sometimes called a "cut" operator,
but Perl 6 has several of them, depending on how much you want to cut).
=head1 New match result and capture variables
The underlying match object is now available via the C<$/>
variable, which is implicitly lexically scoped. All user access to the
most recent match is through this variable, even when
it doesn't look like it. The individual capture variables (such as C<$0>,
C<$1>, etc.) are just elements of C<$/>.
By the way, unlike in Perl 5, the numbered capture variables now
start at C<$0> instead of C<$1>. See below.
=head1 Unchanged syntactic features
The following regex features use the same syntax as in Perl 5:
=over
=item *
Capturing: (...)
=item *
Repetition quantifiers: *, +, and ?
=item *
Alternatives: |
=item *
Backslash escape: \
=item *
Minimal matching suffix: ??, *?, +?
=back
While the syntax of C<|> does not change, the default semantics do
change slightly. We are attempting to concoct a pleasing mixture
of declarative and procedural matching so that we can have the
best of both. In short, you need not write your own tokener for
a grammar because Perl will write one for you. See the section
below on "Longest-token matching".
=head1 Simplified lexical parsing of patterns
Unlike traditional regular expressions, Perl 6 does not require
you to memorize an arbitrary list of metacharacters. Instead it
classifies characters by a simple rule. All glyphs (graphemes)
whose base characters are either the underscore (C<_>) or have
a Unicode classification beginning with 'L' (i.e. letters) or 'N'
(i.e. numbers) are always literal (i.e. self-matching) in regexes. They
must be escaped with a C<\> to make them metasyntactic (in which
case that single alphanumeric character is itself metasyntactic,
but any immediately following alphanumeric character is not).
All other glyphs--including whitespace--are exactly the opposite:
they are always considered metasyntactic (i.e. non-self-matching) and
must be escaped or quoted to make them literal. As is traditional,
they may be individually escaped with C<\>, but in Perl 6 they may
be also quoted as follows.
Sequences of one or more glyphs of either type (i.e. any glyphs at all)
may be made literal by placing them inside single quotes. (Double
quotes are also allowed, with the same interpolative semantics as
the current language in which the regex is lexically embedded.)
Quotes create a quantifiable atom, so while
moose*
quantifies only the 'e' and matches "mooseee", saying
'moose'*
quantifies the whole string and would match "moosemoose".
Here is a table that summarizes the distinctions:
Alphanumerics Non-alphanumerics Mixed
Literal glyphs a 1 _ \* \$ \. \\ \' K\-9\!
Metasyntax \a \1 \_ * $ . \ ' \K-\9!
Quoted glyphs 'a' '1' '_' '*' '$' '.' '\\' '\'' 'K-9!'
In other words, identifier glyphs are literal (or metasyntactic when
escaped), non-identifier glyphs are metasyntactic (or literal when
escaped), and single quotes make everything inside them literal.
Note, however, that not all non-identifier glyphs are currently
meaningful as metasyntax in Perl 6 regexes (e.g. C<\1> C<\_> C<->
C<!>). It is more accurate to say that all unescaped non-identifier
glyphs are I<potential> metasyntax, and reserved for future use.
If you use such a sequence, a helpful compile-time error is issued
indicating that you either need to quote the sequence or define a new
operator to recognize it.
The semicolon character is specifically reserved as a non-meaningful
metacharacter; if an unquoted semicolon is seen, the compiler will
complain that the regex is missing its terminator.
=head1 Modifiers
=over
=item *
The extended syntax (C</x>) is no longer required...it's the default.
(In fact, it's pretty much mandatory--the only way to get back to
the old syntax is with the C<:Perl5>/C<:P5> modifier.)
=item *
There are no C</s> or C</m> modifiers (changes to the meta-characters
replace them - see below).
=item *
There is no C</e> evaluation modifier on substitutions; instead use:
s/pattern/{ doit() }/
or:
s[pattern] = doit()
Instead of C</ee> say:
s/pattern/{ eval doit() }/
or:
s[pattern] = eval doit()
=item *
Modifiers are now placed as adverbs at the I<start> of a match/substitution:
m:g:i/\s* (\w*) \s* ,?/;
Every modifier must start with its own colon. The delimiter must be
separated from the final modifier by whitespace if it would otherwise be taken
as an argument to the preceding modifier (which is true if and only if
the next character is a left parenthesis.)
=item *
The single-character modifiers also have longer versions:
:i :ignorecase
:m :ignoremark
:g :global
:r :ratchet
=item *
The C<:i> (or C<:ignorecase>) modifier causes case distinctions to be
ignored in its lexical scope, but not in its dynamic scope. That is,
subrules always use their own case settings. The amount of case folding
depends on the current context. In byte and codepoint mode, level 1 case folding
is required (as defined in TR18 section 2.4). In grapheme mode level 2 is
required.
The C<:ii> (or C<:samecase>) variant may be used on a substitution to change the
substituted string to the same case pattern as the matched string.
If the pattern is matched without the C<:sigspace> modifier, case
info is carried across on a character by character basis. If the
right string is longer than the left one, the case of the final
character is replicated. Titlecase is carried across if possible
regardless of whether the resulting letter is at the beginning of
a word or not; if there is no titlecase character available, the
corresponding uppercase character is used. (This policy can be
modified within a lexical scope by a language-dependent Unicode
declaration to substitute titlecase according to the orthographic
rules of the specified language.) Characters that carry no case
information leave their corresponding replacement character unchanged.
If the pattern is matched with C<:sigspace>, then a slightly smarter
algorithm is used which attempts to determine if there is a uniform
capitalization policy over each matched word, and applies the same
policy to each replacement word. If there doesn't seem to be a uniform
policy on the left, the policy for each word is carried over word by
word, with the last pattern word replicated if necessary. If a word
does not appear to have a recognizable policy, the replacement word
is translated character for character as in the non-sigspace case.
Recognized policies include:
lc()
uc()
tc()
tclc()
tcuc()
In any case, only the officially matched string part of the pattern
match counts, so any sort of lookahead or contextual matching is not
included in the analysis.
=item *
The C<:m> (or C<:ignoremark>) modifier scopes exactly like C<:ignorecase>
except that it ignores marks (accents and such) instead of case. It is equivalent
to taking each grapheme (in both target and pattern), converting
both to NFD (maximally decomposed) and then comparing the two base
characters (Unicode non-mark characters) while ignoring any trailing
mark characters. The mark characters are ignored only for the purpose
of determining the truth of the assertion; the actual text matched
includes all ignored characters, including any that follow the final
base character.
The C<:mm> (or C<:samemark>) variant may be used on a substitution to change the
substituted string to the same mark/accent pattern as the matched string.
Mark info is carried across on a character by character basis. If
the right string is longer than the left one, the remaining characters
are substituted without any modification. (Note that NFD/NFC distinctions
are usually immaterial, since Perl encapsulates that in grapheme mode.)
Under C<:sigspace> the preceding rules are applied word by word.
=item *
The C<:c> (or C<:continue>) modifier causes the pattern to continue
scanning from the specified position (defaulting to C<($/ ?? $/.to !! 0)>):
m:c($p)/ pattern / # start scanning at position $p
Note that this does not automatically anchor the pattern to the starting
location. (Use C<:p> for that.) The pattern you supply to C<split>
has an implicit C<:c> modifier.
String positions are of type C<StrPos> and should generally be treated
as opaque.
=item *
The C<:p> (or C<:pos>) modifier causes the pattern to try to match only at
the specified string position:
m:pos($p)/ pattern / # match at position $p
If the argument is omitted, it defaults to C<($/ ?? $/.to !! 0)>. (Unlike in
Perl 5, the string itself has no clue where its last match ended.)
All subrule matches are implicitly passed their starting position.
Likewise, the pattern you supply to a Perl macro's C<is parsed>
trait has an implicit C<:p> modifier.
Note that
m:c($p)/pattern/
is roughly equivalent to
m:p($p)/.*? <( pattern )> /
All of C<:g>, C<:ov>, C<:nth>, and C<:x> are incompatible with C<:p> and
will fail, recommending use of C<:c> instead. The C<:ex> modifier is allowed
but will produce only matches at that position.
=item *
The new C<:s> (C<:sigspace>) modifier causes certain whitespace sequences
to be considered "significant"; they are replaced by a whitespace
matching rule, C<< <.ws> >>. Only whitespace sequences immediately following a
matching construct (atom, quantified atom, or assertion) are eligible.
Hence, initial whitespace is ignored at the front of
any regex, to make it easy to write rules that can participate in longest-token-matching
alternations. That is,
m:s/ next cmd '=' <condition>/
is the same as:
m/ next <.ws> cmd <.ws> '=' <.ws> <condition>/
which is effectively the same as:
m/ next \s+ cmd \s* '=' \s* <condition>/
But in the case of
m:s{(a|\*) (b|\+)}
or equivalently,
m { (a|\*) <.ws> (b|\+) }
C<< <.ws> >> can't decide what to do until it sees the data.
It still does the right thing. If not, define your own C<< ws >>
and C<:sigspace> will use that.
Whitespace is ignored not just at the front of any rule that might
participate in longest-token matching, but in the front of any
alternative within an explicit alternation as well, for the same
reason. If you want to match sigspace before a set of alternatives,
place your whitespace outside of the brackets containing the alternation.
When you write
rule TOP { ^ <stuff> $ }
this is the same as
token TOP { ^ <.ws> <stuff> <.ws> $ <.ws> }
but note that the final C<< <.ws> >> always matches the null string, since C<$> asserts end of string.
Also, if your C<TOP> rule does not anchor with C<^>, it might not match initial whitespace.
Specifically, the following constructs turn following whitespace into sigspace:
any atom or quantified atom
$foo @bar
'a' "$b"
^ $ ^^ $$
(...) [...] <...> as a whole atoms
(...)* [...]* <...>* as quantified atoms
<( and )>
« and » (but don't use « that way!)
and these do not:
opening ( or [
| or ||
& or &&
** % or %%
:foo declarations, including :my and :sigspace itself
{...}
When we say sigspace can follow either an atom or a quantified atom, we
mean that it can come between an atom and its quantifier:
ms/ <atom> * / # means / [<atom><.ws>]* /
(If each atom matches whitespace, then it doesn't need to match after the
quantifier.)
In general you don't need to use C<:sigspace> within grammars because
the parser rules automatically handle whitespace policy for you.
In this context, whitespace often includes comments, depending on
how the grammar chooses to define its whitespace rule. Although the
default C<< <.ws> >> subrule recognizes no comment construct, any
grammar is free to override the rule. The C<< <.ws> >> rule is not
intended to mean the same thing everywhere.
It's also possible to pass an argument to C<:sigspace> specifying
a completely different subrule to apply. This can be any rule, it
doesn't have to match whitespace. When discussing this modifier, it is
important to distinguish the significant whitespace in the pattern from
the "whitespace" being matched, so we'll call the pattern's whitespace
I<sigspace>, and generally reserve I<whitespace> to indicate whatever
C<< <.ws> >> matches in the current grammar. The correspondence
between sigspace and whitespace is primarily metaphorical, which is
why the correspondence is both useful and (potentially) confusing.
The C<:ss> (or C<:samespace>) variant may be used on substitutions to
do smart space mapping. For each sigspace-induced call to C<< <ws> >>
on the left, the matched whitespace is copied over to the corresponding
slot on the right, as represented by a single whitespace character
in the replacement string wherever space replacement is desired.
If there are more whitespace slots on the right than the left, those
righthand characters remain themselves. If there are not enough
whitespace slots on the right to map all the available whitespace
slots from the match, the algorithm tries to minimize information
loss by randomly splicing "common" whitespace characters out of the
list of whitespace. From least valuable to most, the pecking order is:
spaces
tabs
all other horizontal whitespace, including Unicode
newlines (including crlf as a unit)
all other vertical whitespace, including Unicode
The primary intent of these rules is to minimize format disruption
when substitution happens across line boundaries and such. There is,
of course, no guarantee that the result will be exactly what a human would
do.
The C<:s> modifier is considered sufficiently important that
match variants are defined for them:
ms/match some words/ # same as m:sigspace
ss/match some words/replace those words/ # same as s:samespace
Note that C<ss///> is defined in terms of C<:ss>, so:
$_ = "a b\nc\td";
ss/b c d/x y z/;
ends up with a value of "C<a x\ny\tz>".
=item *
New modifiers specify Unicode level:
m:bytes / .**2 / # match two bytes
m:codes / .**2 / # match two codepoints
m:graphs / .**2 / # match two language-independent graphemes
m:chars / .**2 / # match two characters at current max level
There are corresponding pragmas to default to these levels. Note that
the C<:chars> modifier is always redundant because dot always matches
characters at the highest level allowed in scope. This highest level
may be identical to one of the other three levels, or it may be more
specific than C<:graphs> when a particular language's character rules
are in use. Note that you may not specify language-dependent character
processing without specifying I<which> language you're depending on.
[Conjecture: the C<:chars> modifier could take an argument specifying
which language's rules to use for this match.]
=item *
The new C<:Perl5>/C<:P5> modifier allows Perl 5 regex syntax to be
used instead. (It does not go so far as to allow you to put your
modifiers at the end.) For instance,
m:P5/(?mi)^(?:[a-z]|\d){1,2}(?=\s)/
is equivalent to the Perl 6 syntax:
m/ :i ^^ [ <[a..z]> || \d ] ** 1..2 <?before \s> /
=item *
Any integer modifier specifies a count. What kind of count is
determined by the character that follows.
=item *
If followed by an C<x>, it means repetition. Use C<:x(4)> for the
general form. So
s:4x [ (<.ident>) '=' (\N+) $$] = "$0 => $1";
is the same as:
s:x(4) [ (<.ident>) '=' (\N+) $$] = "$0 => $1";
which is almost the same as:
s:c[ (<.ident>) '=' (\N+) $$] = "$0 => $1" for 1..4;
except that the string is unchanged unless all four matches are found.
However, ranges are allowed, so you can say C<:x(1..4)> to change anywhere
from one to four matches.
=item *
If the number is followed by an C<st>, C<nd>, C<rd>, or C<th>, it means
find the I<N>th occurrence. Use C<:nth(3)> for the general form. So
s:3rd/(\d+)/@data[$0]/;
is the same as
s:nth(3)/(\d+)/@data[$0]/;
which is the same as:
m/(\d+)/ && m:c/(\d+)/ && s:c/(\d+)/@data[$0]/;
The argument to C<:nth> is allowed to be a list of integers, but such a list
should be monotonically increasing. (Values which are less than or equal to
any previous value will be ignored.) So:
:nth(2,4,6...*) # return only even matches
:nth(1,1,*+*...*) # match only at 1,2,3,5,8,13...
This option is no longer required to support smartmatching. You can grep a list
of integers if you really need that capability:
:nth(grep *.oracle, 1..*)
If both C<:nth> and C<:x> are present, the matching routine looks for submatches
that match with C<:nth>. If the number of post-nth matches is compatible with
the constraint in C<:x>, the whole match succeeds with the highest possible
number of submatches. The combination of C<:nth> and C<:x> typically only
makes sense if C<:nth> is not a single scalar.
=item *
With the new C<:ov> (C<:overlap>) modifier, the current regex will
match at all possible character positions (including overlapping)
and return all matches in list context, or a disjunction of matches
in item context. The first match at any position is returned.
The matches are guaranteed to be returned in left-to-right order with
respect to the starting positions.
$str = "abracadabra";
if $str ~~ m:overlap/ a (.*) a / {
@substrings = slice @(); # bracadabr cadabr dabr br
}
=item *
With the new C<:ex> (C<:exhaustive>) modifier, the current regex will
match every possible way (including overlapping) and return a list of
all matches.
The matches are guaranteed to be returned in left-to-right order with
respect to the starting positions. The order within each starting
position is not guaranteed and may depend on the nature of both the
pattern and the matching engine. (Conjecture: or we could enforce
backtracking engine semantics. Or we could guarantee no order at all
unless the pattern starts with "::" or some such to suppress DFAish
solutions.)
$str = "abracadabra";
if $str ~~ m:exhaustive/ a (.*?) a / {
say "@()"; # br brac bracad bracadabr c cad cadabr d dabr br
}
Note that the C<~~> above can return as soon as the first match is found,
and the rest of the matches may be performed lazily by C<@()>.
=item *
The new C<:rw> modifier causes this regex to I<claim> the current
string for modification rather than assuming copy-on-write semantics.
All the captures in C<$/> become lvalues into the string, such
that if you modify, say, C<$1>, the original string is modified in
that location, and the positions of all the other fields modified
accordingly (whatever that means). In the absence of this modifier
(especially if it isn't implemented yet, or is never implemented),
all pieces of C<$/> are considered copy-on-write, if not read-only.
[Conjecture: this should really associate a pattern with a string variable,
not a (presumably immutable) string value.]
=item *
The new C<:r> or C<:ratchet> modifier causes this regex to not backtrack by default.
(Generally you do not use this modifier directly, since it's implied by
C<token> and C<rule> declarations.) The effect of this modifier is
to imply a C<:> after every atom, including but not limited to
C<*>, C<+>, and C<?> quantifiers, as well as alternations. Explicit
backtracking modifiers on quantified atoms, such as C<**>, will override this.
(Note: for portions of patterns subject to longest-token analysis, a C<:>
is ignored in any case, since there will be no backtracking necessary.)
=item *
The C<:i>, C<:s>, C<:Perl5>, and Unicode-level modifiers can be
placed inside the regex (and are lexically scoped):
m/:s alignment '=' [:i left|right|cent[er|re]] /
As with modifiers outside, only parentheses are recognized as valid
brackets for args to the adverb. In particular:
m/:foo[xxx]/ Parses as :foo [xxx]
m/:foo{xxx}/ Parses as :foo {xxx}
m/:foo<xxx>/ Parses as :foo <xxx>
=item *
User-defined modifiers will be possible:
m:fuzzy/pattern/;
=item *
User-defined modifiers can also take arguments, but only in parentheses:
m:fuzzy('bare')/pattern/;
=item *
To use parens for your delimiters you have to separate:
m:fuzzy (pattern);
or you'll end up with:
m:fuzzy(fuzzyargs); pattern ;
=item *
Any grammar regex is really just a kind of method, and you may
declare variables in such a routine using a colon followed by any
scope declarator parsed by the Perl 6 grammar, including C<my>,
C<our>, C<state>, and C<constant>. (As quasi declarators, C<temp>
and C<let> are also recognized.) A single statement (up through
a terminating semicolon) is parsed as normal Perl 6 code:
token prove-nondeterministic-parsing {
:my $threshold = rand;
'maybe' \s+ <it($threshold)>
}
Such declarations do not terminate longest-token-matching,
so an otherwise useless declaration may be used as a peg
to hang side effects on without changing how the subsequent
pattern matches:
rule breaker {
:state $ = say "got here at least once";
...
}
=back
=head2 Allowed modifiers
Some modifiers are allowed in all possible places where modifiers can occur,
but not all of them.
In general, a modifier that affects the compilation of a regex (like C<:i>)
must be known at compile time. A modifier that affects only the calling
behaviour, and not the regex itself (eg. C<:pos>, C<:overlap>, C<:x(4)>) may
only appear on constructs that involve a call (like C<m//> and C<s///>), and
not on C<rx//>. Finally overlapping is disallowed on substitutions, while
adverbs that affect modifications (eg. C<:samecase>) are only allowed on
substitutions.
These principle result in the following rules:
=over
=item *
The C<:ignorecase>, C<:ignoremark>, C<:sigspace>, C<:ratchet> and C<:Perl5>
modifiers and their short forms are allowed everywhere: inside a regex,
and on C<m//>, C<rx//> and C<s///> constructs. An implementation may require
that their value is known at compile time, and give a compile-time error
message if that is not the case.
rx:i/ hello / # OK
rx:i(1) /hello/ # OK
my $i = 1;
rx:i($i) /hello/ # may error out at compile time
=item *
The C<:samecase>, C<:samespace> and C<:samemark> modifiers (and their short
forms) modifiers are only allowed on substitutions (C<s///> and C<s[] = ...>).
=item *
The C<:overlap> and C<:exhaustive> modifiers (and their short forms) are only
allowed on matches (ie C<m//>), not on substitutions or regex quotes.
=item *
The C<:pos>, C<:continue>, C<:x> and C<:nth> modifiers and their aliases are
only allowed on constructs that involve immediate calls, eg. C<m//> and C<s///>
(but not on C<rx//>).
=item *
The C<:dba> adverb is only allowed inside a regex.
=back
=head1 Changed metacharacters
=over
=item *
A dot C<.> now matches I<any> character including newline. (The C</s>
modifier is gone.)
=item *
C<^> and C<$> now always match the start/end of a string, like the old
C<\A> and C<\z>. (The C</m> modifier is gone.) On the right side of
an embedded C<~~> or C<!~~> operator they always match the start/end
of the indicated submatch because that submatch is logically being
treated as a separate string.
=item *
A C<$> no longer matches an optional preceding C<\n> so it's necessary
to say C<\n?$> if that's what you mean.
=item *
C<\n> now matches a logical (platform independent) newline, not just C<\x0a>.
See TR18 section 1.6 for a list of logical newlines.
=item *
The C<\A>, C<\Z>, and C<\z> metacharacters are gone.
=back
=head1 New metacharacters
=over
=item *
Because C</x> is default:
=over
=item *
An unquoted C<#> now always introduces a comment. If followed
by a backtick and an opening bracket character,
it introduces an embedded comment that terminates with the closing
bracket. Otherwise the comment terminates at the newline.
=item *
Whitespace is now always metasyntactic, i.e. used only for layout
and not matched literally (but see the C<:sigspace> modifier described above).
=back
=item *
C<^^> and C<$$> match line beginnings and endings. (The C</m>
modifier is gone.) They are both zero-width assertions. C<$$>
matches before any C<\n> (logical newline), and also at the end of
the string if the final character was I<not> a C<\n>. C<^^> always
matches the beginning of the string and after any C<\n> that is not
the final character in the string.
=item *
C<.> matches an I<anything>, while C<\N> matches an I<anything except
what C<\n> matches>. (The C</s> modifier is gone.) In particular, C<\N> matches
neither carriage return nor line feed.
=item *
The new C<&> metacharacter separates conjunctive terms. The patterns
on either side must match with the same beginning and end point.
Note: if you don't want your two terms to end at the same point,
then you really want to use a lookahead instead.
As with the disjunctions C<|> and C<||>, conjunctions come in both
C<&> and C<&&> forms. The C<&> form is considered declarative rather than
procedural; it allows the compiler and/or the
run-time system to decide which parts to evaluate first, and it is
erroneous to assume either order happens consistently. The C<&&>
form guarantees left-to-right order, and backtracking makes the right
argument vary faster than the left. In other words, C<&&> and C<||> establish
sequence points. The left side may be backtracked into when backtracking
is allowed into the construct as a whole.
The C<&> operator is list associative like C<|>, but has slightly
tighter precedence. Likewise C<&&> has slightly tighter precedence
than C<||>. As with the normal junctional and short-circuit operators,
C<&> and C<|> are both tighter than C<&&> and C<||>.
=item *
The C<~~> and C<!~~> operators cause a submatch to be performed on
whatever was matched by the variable or atom on the left. String
anchors consider that submatch to be the entire string. So, for
instance, you can ask to match any identifier that does not contain
the word "moose":
<ident> !~~ 'moose'
In contrast
<ident> !~~ ^ 'moose' $
would allow any identifier (including any identifier containing
"moose" as a substring) as long as the identifier as a whole is not
equal to "moose". (Note the anchors, which attach the submatch to the
beginning and end of the identifier as if that were the entire match.)
When used as part of a longer match, for clarity it might be good to
use extra brackets:
[ <ident> !~~ ^ 'moose' $ ]
The precedence of C<~~> and C<!~~> fits in between the junctional and
sequential versions of the logical operators just as it does in normal
Perl expressions (see S03). Hence
<ident> !~~ 'moose' | 'squirrel'
parses as
<ident> !~~ [ 'moose' | 'squirrel' ]
while
<ident> !~~ 'moose' || 'squirrel'
parses as
[ <ident> !~~ 'moose' ] || 'squirrel'
=item *
The C<~> operator is a helper for matching nested subrules with a
specific terminator as the goal. It is designed to be placed between an
opening and closing bracket, like so:
'(' ~ ')' <expression>
However, it mostly ignores the left argument, and operates on the next
two atoms (which may be quantified). Its operation on those next
two atoms is to "twiddle" them so that they are actually matched in
reverse order. Hence the expression above, at first blush, is merely
shorthand for:
'(' <expression> ')'
But beyond that, when it rewrites the atoms it also inserts the
apparatus that will set up the inner expression to recognize the
terminator, and to produce an appropriate error message if the
inner expression does not terminate on the required closing atom.
So it really does pay attention to the left bracket as well, and it
actually rewrites our example to something more like:
$<OPEN> = '(' <SETGOAL: ')'> <expression> [ $GOAL || <FAILGOAL> ]
Note that you can use this construct to set up expectations for
a closing construct even when there's no opening bracket:
<?> ~ ')' \d+
Here <?> returns true on the first null string.
By default the error message uses the name of the current rule as an
indicator of the abstract goal of the parser at that point. However,
often this is not terribly informative, especially when rules are named
according to an internal scheme that will not make sense to the user.
The C<:dba("doing business as")> adverb may be used to set up a more informative name for
what the following code is trying to parse:
token postfix:sym<[ ]> {
:dba('array subscript')
'[' ~ ']' <expression>
}
Then instead of getting a message like:
Unable to parse expression in postfix:sym<[ ]>; couldn't find final ']'
you'll get a message like:
Unable to parse expression in array subscript; couldn't find final ']'
(The C<:dba> adverb may also be used to give names to alternations
and alternatives, which helps the lexer give better error messages.)
=back
=head1 Bracket rationalization
=over
=item *
C<(...)> still delimits a capturing group. However the ordering of these
groups is hierarchical rather than linear. See L<Nested subpattern captures>.
=item *
C<[...]> is no longer a character class.
It now delimits a non-capturing group.
A character class is now specified using C<< <[...]> >>.
See also L<Extensible metasyntax>.
=item *
C<{...}> is no longer a repetition quantifier.
It now delimits an embedded closure. It is always considered
procedural rather than declarative; it establishes a sequence point
between what comes before and what comes after. (To avoid this
use the C<< <?{...}> >> assertion syntax instead.) A closure
within a regex establishes its own lexical scope.
=item *
You can call Perl code as part of a regex match by using a closure.
Embedded code does not usually affect the match--it is only used
for side-effects:
/ (\S+) { print "string not blank\n"; $text = $0; }
\s+ { print "but does contain whitespace\n" }
/
An B<explicit> reduction using the C<make> function generates the
I<abstract syntax tree> object (I<abstract object> or I<ast> for short)
for this match:
/ (\d) { make $0.sqrt } Remainder /;
This has the effect of capturing the square root of the numified
string, instead of the string. The C<Remainder> part is matched and
returned as part of the C<Match> object but is not returned
as part of the abstract object. Since the abstract object usually
represents the top node of an abstract syntax tree, the abstract object
may be extracted from the C<Match> object by use of the C<.ast> method.
A second call to C<make> overrides any previous call to C<make>.
C<make> is also available as a method on each match object.
Within a closure, the instantaneous
position within the search is denoted by the C<$¢.pos> method.
As with all string positions, you must not treat it
as a number unless you are very careful about which units you are
dealing with.
The C<Cursor> object can also return the original item that we are
matching against; this is available from the C<.orig> method.
The closure is also guaranteed to start with a C<$/> C<Match> object
representing the match so far. However, if the closure does its own
internal matching, its C<$/> variable will be rebound to the result
of I<that> match until the end of the embedded closure. (The match
will actually continue with the current value of the C<$¢> object after
the closure. C<$/> and C<$¢> just start out the same in your closure.)
=item *
It can affect the match if it calls C<fail>:
/ (\d+) { $0 < 256 or fail } /
Since closures establish a sequence point, they are guaranteed to be
called at the canonical time even if the optimizer could prove that
something after them can't match. (Anything before is fair game,
however. In particular, a closure often serves as the terminator
of a longest-token pattern.)
=item *
The general repetition specifier is now C<**> for greedy matching,
with a corresponding C<**?> for frugal matching. (All such quantifier
modifiers now go directly after the C<**>.) Space is allowed on either
side of the complete quantifier, but only the space before the C<**> will
be considered significant under C<:sigspace> and match between repetitions.
(Sigspace after the entire construct matches once after the all repetitions
are found.)
The next token constrains how many times the pattern on the left must match.