Link to home
Start Free TrialLog in
Avatar of tel2
tel2Flag for New Zealand

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
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tel2

ASKER

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
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tel2

ASKER

For performance, ozo?
yes
Avatar of tel2

ASKER

Thanks.