zemane has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm trying to match a regular expression that may contain a special char that I want it to be ignored. For example, suppose I am looking for the pattern 'aabb' and anywhere in the string I could have the special char \xFF.

So my string could be any of these:

$str = "a\xFFabb"; $str = "aa\xFFbb"; $str = "aabb\xFF";
And I want the following code to match successfully:

if ($str =~ "aabb") { print "match found\n"; } else { print "no match\n"; }
Is there any way to tell Perl to ignore a certain special character when looking for a match?

I don't want to remove the special char from the string because later on I want to find this special char and use its position to insert other stuff into the string. So, this special char is used as a marker for future insertions.

Replies are listed 'Best First'.
Re: Can I make Perl ignore a special char when matching?
by GrandFather (Saint) on Jul 23, 2008 at 22:49 UTC

    Why not create a copy of the string with the special char removed and use that for the initial matching?

    Alternatively you could:

    use strict; use warnings; my $matchStr = 'aabb'; my $match = "\xff?" . join ("\xff?", split '', $matchStr) . "\xff?"; my $str = "aa\xffbb"; if ($str =~ $match) { print "Matched"; } else { print "No match"; }

    Perl is environmentally friendly - it saves trees
Re: Can I make Perl ignore a special char when matching?
by aquarium (Curate) on Jul 24, 2008 at 01:31 UTC
    putting things of different semantic/logical nature into one place--especially with extensibility in mind--is bound to cause problems sooner or later. better to have a separate variable or other structure attached to the string, which will contain any special things like special placemarkers. Then you have a clean string variable to match against.
    the hardest line to type correctly is: stty erase ^H
Re: Can I make Perl ignore a special char when matching?
by jethro (Monsignor) on Jul 23, 2008 at 22:55 UTC
    Just copy $str to another variable, remove the special char from that copy before you try to match it.