Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Can a regular expression include an arbitrary string variable?

by davido (Cardinal)
on Oct 17, 2019 at 05:01 UTC ( #11107579=note: print w/replies, xml ) Need Help??

in reply to Can a regular expression include an arbitrary string variable?

Yes, regular expressions can interpolate variables into them:

my $string_to_find = 'hidden'; my @array_to_search = qw(Foo whathiddenever Bar 12hidden456); say "Found $_" for grep {m/\Q$string_to_find/} @array_to_search;

You may also decide you don't need a pattern match, and if you can come to that conclusion you avoid the problem of treating strings as code:

say "Found $_" for grep {index($_, $string_to_find) > -1} @array_to_se +arch;

You can observe the rules of how interpolation works in regular expressions by reading perlop and perlre. The index function is also documented at perldoc -f index.

An advantage of the index approach is that you're not exposing the regular expression mini-language and engine to arbitrary strings, which could contain code. It's also lighter-weight, not invoking the engine.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11107579]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2019-12-13 10:04 GMT
Find Nodes?
    Voting Booth?

    No recent polls found