Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

How do you use a variable value within a regular expression pattern properly?

by Anonymous Monk
on Sep 11, 2017 at 11:24 UTC ( #1199079=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
If I have the following code:
$myvar="one"; $string="oneREC:riugfryfgfyug";

and I want to do this pattern matching:

it does not work because REC is right after the value of $myvar. Only if I separate them, e.g. $string="one#REC:riugfryfgfyug";
it does the pattern matching. Can you tell me what I am doing wrong?

Replies are listed 'Best First'.
Re: How do you use a variable value within a regular expression pattern properly? (updated)
by haukex (Abbot) on Sep 11, 2017 at 11:43 UTC

    As an alternative to what 1nickt showed, there's also the /x modifier that allows you to insert whitespace in your regex, which also improves readability:

    if( $string=~/ ^ $myvar REC: (.*) /x )

    Also, Mind the meta!, that means if your $myvar contains any characters like the dot (.) and you don't want these to be interpreted as regex special characters, or any whitespace in the variable to be ignored under /x, then you need to wrap your string in \Q...\E (see also quotemeta):

    if( $string=~/ ^ \Q$myvar\E REC: (.*) /x )

    Update: Added links to docs. Also added bit about whitespace in the variable under /x.

    Update 2: Just to be clear, I recommend you always use \Q...\E, even if you don't use /x, unless you specifically want regex metacharacters in $myvar to be treated as such and it comes from a trusted source! That is, if($string=~/^\Q$myvar\EREC:(.*)/)

Re: How do you use a variable value within a regular expression pattern properly?
by 1nickt (Prior) on Sep 11, 2017 at 11:30 UTC

    Use braces, like: "${myvar}REC".

    The way forward always starts with a minimal test.
      Thank you very much!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1199079]
Approved by haukex
Front-paged by davies
[ambrus]: the annotation mentions Brisbane as even worse, and I add Debrecen
[marto]: :)
[ambrus]: robby: dunno, I would like to visit London some time, although there are other places I'd like to visit more
[marto]: "Okay, sure, there are in fact museums and art galleries and other culturally enlightened things to do in Glasgow, but that wouldn't have made a funny comic"
LanX .oO( cemetery breweries ? )

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2017-12-15 11:09 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (431 votes). Check out past polls.