Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate a variable into a regex-pattern in the regex part of a substitution?

What do I have to change here to make it work?

my $str = "start middle end";
my $regex = / start ( .+ ) end /;
$str.=subst( / <$regex> /, { $0 } ); # dies: Use of Nil in string context
say "[$str]";
like image 502
sid_com Avatar asked Apr 19 '19 11:04

sid_com


People also ask

How do you use a variable inside a regex pattern?

let year = 'II'; let sem = 'I'; let regex = new RegExp(`${year} B. Tech ${sem} Sem`, "g"); You need to pass the options to the RegExp constructor, and remove the regex literal delimiters from your string.

Can you put a variable inside a regex?

It's not reeeeeally a thing. There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor.

How do I create a dynamic expression 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.

What does (?: Mean in regex?

(?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.


1 Answers

The problem is that interpolating a regex into another regex via the <$regex> syntax will not install a result in the match variable. There's two ways to get around this:

  • The easiest way is to just use the regex directly in subst, i.e. $str .= subst($regex, { $0 });
  • Give the interpolated regex an explicit name and access the result via that, i.e. $str .= subst( / <foo=$regex> /, { $<foo>[0] });

Both of these should work fine.

like image 147
timotimo Avatar answered Oct 07 '22 04:10

timotimo