Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to make a regex matching exactly zero characters in Perl 6?

Tags:

raku

How to explicitly define a regex (numbered or named capturing group), which always matches exactly zero characters?

> "abc" ~~ m/()abc/
===SORRY!=== Error while compiling:
Null regex not allowed

> my regex null {}
===SORRY!=== Error while compiling:
Null regex not allowed

> my regex null {<[]>}
regex null {<[]>}
> "abc" ~~ m/<null>abc/
False

Of course I can use something like the following, but I'm looking for an idiomatic way of doing it.

> my regex null {a ** 0}
regex null {a ** 0}
> "abc" ~~ m/<null>abc/
「abc」
 null => 「」

UPD: This works, but is it the best way?

> my regex null { '' }
regex null { '' }
> "abc" ~~ m/<null>abc/
「abc」
 null => 「」
> "abc" ~~ m/('') abc/
「abc」
 0 => 「」
like image 708
Eugene Barsky Avatar asked Jan 29 '23 08:01

Eugene Barsky


1 Answers

The assertion that always succeeds and matches 0 characters is: <?>.

For example:

say so 'foo' ~~ / <?> 'foo' /;
# output: True

As raiph pointed out, the corresponding negative version, which always fails, is <!>. I've used this to insert error messages when part of a parse should not be reached if the input is valid. That section of the regex might read:

\d || [ { note "Error: the previous token must be followed by a number."; } <!> ]
like image 145
piojo Avatar answered May 23 '23 10:05

piojo