Perl6 regex match conjunction && returns True if all parts in the conjunction matches the same substring instead of the whole string:
> my $a="123abc456def";
123abc456def
> so $a ~~ m/ 23 && ef /
False
It is False because "23" in the conjunction matched "23" substring in $a, but this substring does not match "ef" in the conjunction. This is a little counter-intuitive because it is easier to interpret $a~~m/23&&ef/ as "$a matches 23 and $a matches ef" than as "$a has a substring that matches 23 and this substring also matches ef".
If I have n regexes and I want to see if all these n regexes match the same whole string rather than match the same substring part of the whole string, then what is the best way to write the perl6 expression?
In the example, I really mean to do
so (($a ~~ /23/) && ($a ~~ /ef/))
If the number of regexes is large, then the above is harder to write except with a loop:
so (gather {for @myRegexes { take $a ~~ / $_ /; } }).all
Is there a simpler way?
With alternations, it is much easier to read as "$a matches 23 or $a matches ef" rather than "the part of $a that matches 23 or matches ef":
> so $a ~~ m/ 23 || ef /
True
Thanks !
lisprog
You can use a Junction
of the two regexes in order to only mention $a
once.
my $a = 'abcdef12345'; say so $a ~~ /23/ & /ef/ # True
my $a = 'abcde12345'; say so $a ~~ /23/ & /ef/ # False
my $a = 'abcdef1245'; say so $a ~~ /23/ & /ef/ # False
To form the junction from an array of regexes, call .all
on the array.
If it's really just literal strings to find, then contains
is likely to run quite a bit faster:
my $a = 'abcdef12345'; say so $a.contains(all('23', 'ef')) # True
my $a = 'abcde12345'; say so $a.contains(all('23', 'ef')) # False
my $a = 'abcdef1245'; say so $a.contains(all('23', 'ef')) # False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With