Suppose i want to match words with at least 4 letters, (and store them in an array), I have written the following regex, which works fine:
if ( $text ~~ m:g/(\w ** 4..*)/ )
{
my @words = $/;
...
}
The quantifier being from 4 to unlimited
**4..*
Now if I try to substitute 4 with a scalar $min_length. Both:
if ($text ~~ m:g/(\w ** $::min_length..*)/)
and:
if ($text ~~ m:g/(\w ** <$::min_length>..*)/)
results in an error at compilation: Quantifier quantifies nothing
Is there a way for having a scalar as a quantifier?
When the right-hand side of the **
quantifier is not a number or range literal, but an arbitrary Perl 6 expression, you have to enclose it in braces:
my $text = "The quick brown fox jumps over the lazy dog.";
my $min-length = 4;
my @words = $text.comb(/ \w ** {$min-length .. *} /);
.say for @words;
Output:
quick
brown
jumps
over
lazy
I think using .split
is a more natural fit, together with .grep
:
my $text = "The quick brown fox jumps over the lazy dog.";
my $min-length = 4;
say $text.split(/\W+/).grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy)
If you define words as the characters between whitespace, you can even use the .words
method:
say $text.words.grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy dog.)
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