M
Markus Dehmann
I have a pattern that I want to match against some text. The pattern may
contain some chars that happen to be metachars, but I don't want them to
be interpreted as metachars:
my $pattern = 'Hello...?';
$_ = 'Oh Hello x';
if(m/$pattern/){
print "Oh no, it matches!\n"; # it matches indeed!
}
How do I prepare the $pattern properly before using it in the regexp?
I used something like this:
sub encode {
my $s = $_[0];
$s =~ s/(.)/sprintf "\\x%x",ord($1)/ge;
return $s;
}
to encode the pattern before using it in the regexp, but I think it's
inefficient and inelegant...?
Does anyone have a better escape function?
Thanks!
Markus
P.S.: I'm sorry if this is a FAQ (it should be!), but I googled and
didn't find anything.
contain some chars that happen to be metachars, but I don't want them to
be interpreted as metachars:
my $pattern = 'Hello...?';
$_ = 'Oh Hello x';
if(m/$pattern/){
print "Oh no, it matches!\n"; # it matches indeed!
}
How do I prepare the $pattern properly before using it in the regexp?
I used something like this:
sub encode {
my $s = $_[0];
$s =~ s/(.)/sprintf "\\x%x",ord($1)/ge;
return $s;
}
to encode the pattern before using it in the regexp, but I think it's
inefficient and inelegant...?
Does anyone have a better escape function?
Thanks!
Markus
P.S.: I'm sorry if this is a FAQ (it should be!), but I googled and
didn't find anything.