tel2
asked on
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
For performance, ozo?
yes
ASKER
Thanks.
ASKER
In your first solution, I guess I could omit the '\E' in this case.
Thank you. That's just what I was after.
tel2