Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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

by AnomalousMonk (Archbishop)
on Oct 17, 2019 at 02:47 UTC ( [id://11107574]=note: print w/replies, xml ) Need Help??


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

I'm not quite sure what you mean by "arbitrary string variable" and "unknown in advance", but maybe something like:

c:\@Work\Perl\monks>perl -wMstrict -le "chomp(my $string_to_find = <STDIN>); ;; my @array_to_search = qw(Foo whathiddenever Bar 12hidden456); ;; for my $s (@array_to_search) { print qq{'$s' has '$string_to_find'} if $s =~ $string_to_find; } " hidden 'whathiddenever' has 'hidden' '12hidden456' has 'hidden'

Update: In general, strings and, better yet, regex objects created by  qr// (see Regexp Quote-Like Operators in perlop) can be interpolated into and thus used to compose other regex objects:

c:\@Work\Perl\monks>perl -wMstrict -le "chomp(my $string_to_find = <STDIN>); ;; my @array_to_search = qw(Foo whathi$denever Bar 12hi$den456); ;; my $rx_search = qr{ (?<= \d) \Q$string_to_find\E (?= \d) }xms; ;; for my $s (@array_to_search) { print qq{'$s' has '$string_to_find'} if $s =~ $rx_search; } " hi$den '12hi$den456' has 'hi$den'
This illustrates both interpolation for composition and metaquoting with  \Q ... \E of an interpolated variable. See Quote and Quote-like Operators in perlop, perlre.


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-19 06:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found