• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • Last Modified:

Perl regex ignoring [] meta characters

Hi Experts,

I'm having trouble with a Perl regex which tests whether one string is contained in another.  In real life, the data comes from a file and a database, but the code snippet below demonstrates the issue:

    $var1 = 'A [B:2013-03] C';
    $var2 = '[B:2013-03]';
    print "Match!\n" if $var1 =~ /$var2/;

The above gives this error message:
Invalid [] range "3-0" in regex; marked by <-- HERE in m/[B:2013-0 <-- HERE 3]/ at ./sub.pl line 3.

How can I best avoid this problem and get the match to work by ignoring the meta characters?

I know I could escape the [] in $var2, like this:
    $var2 = '\[B:2013-03\]';
but I'm hoping there's a cleaner way.

Thanks.
tel2
0
tel2
Asked:
tel2
  • 3
  • 3
2 Solutions
 
ozoCommented:
$var1 =~ /\Q$var2\E/
or
index($var1,$var2) >= 0
0
 
tel2Author Commented:
Well said, ozo.  TIMTOWTDI.

In your first solution, I guess I could omit the '\E' in this case.

Thank you.  That's just what I was after.
tel2
0
 
ozoCommented:
Or, if you are testing many $var1's with the same $var2, you may want to first do
$var2 = qr/\Q$var2/;
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
tel2Author Commented:
For performance, ozo?
0
 
ozoCommented:
yes
0
 
tel2Author Commented:
Thanks.
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now