Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate a variable into a regular expression

Tags:

regex

raku

I am used to Perl but a Perl 6 newbie

I want to host a regular expression in a text variable, like I would have done in perl5:

my $a = 'abababa';
my $b = '^aba';
if ($a =~ m/$b/) {
        print "True\n";
} else {
        print "False\n";
}

But if I do the same in Perl6 it doesn't work:

my $a = 'abababa';
my $b = '^aba';

say so $a ~~ /^aba/;  # True
say so $a ~~ /$b/;    # False

I'm puzzled... What am I missing?

like image 779
mmzz Avatar asked Aug 04 '17 13:08

mmzz


People also ask

How do you interpolate a variable?

Use a template literal to interpolate a variable in a string, e.g hello ${myVar} . Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

Can I use a variable in regex?

To make a regular expression dynamic, we can use a variable to change the regular expression pattern string by changing the value of the variable. But how do we use dynamic (variable) string as a regex pattern in JavaScript? We can use the JavaScript RegExp Object for creating a regex pattern from a dynamic string.

Can I use a variable in regex python?

Can you put a variable in regex Python? Use string formatting to use a string variable within a regular expression. Use the syntax "%s" % var within a regular expression to place the value of var in the location of the string "%s" .


2 Answers

You need to have a closer look at Quoting Constructs.

For this case, enclose the part of the LHS that is a separate token with angle brackets or <{ and }>:

my $a = 'abababa';
my $b = '^aba';
say so $a ~~ /<$b>/;       # True, starts with aba
say so $a ~~ /<{$b}>/;     # True, starts with aba

my $c = '<[0..5]>'
say so $a ~~ /<$c>/;       # False, no digits 1 to 5 in $a
say so $a ~~ /<{$c}>/;     # False, no digits 1 to 5 in $a

enter image description here

Another story is when you need to pass a variable into a limiting quantifier. That is where you need to only use braces:

my $ok = "12345678";
my $not_ok = "1234567";
my $min = 8;
say so $ok ~~ / ^ \d ** {$min .. *} $ /;         # True, the string consists of 8 or more digits
say so $not_ok ~~ / ^ \d ** {$min .. *} $ /;     # False, there are 7 digits only

enter image description here

like image 69
Wiktor Stribiżew Avatar answered Oct 05 '22 12:10

Wiktor Stribiżew


Is there a reason why you don't pick the regex object for these types of uses?

my $a = 'abababa';
my $b = rx/^aba/;

say so $a ~~ /^aba/;  # True
say so $a ~~ $b;     # True
like image 20
nxadm Avatar answered Oct 05 '22 12:10

nxadm