Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regexp question

Status
Not open for further replies.

demejanos

Programmer
Jun 12, 2008
7
HU
Hi!

I need to use regular expressions with backslash, both in the string and the regexp too. I cant make it work!

With quotemeta or "" it takes out the single backslash from it, but works. (I don't want this)

Any other possibilities I tried, didn't worked.

my $string = 'words AUTH\SYS words';
my $regxp = '.*AUTH\SYS.*';

print "OK" if ($string =~ /$regxp/);

Thanks for any help!
 
Even in single quotes, \\ gets escaped down to \. In a regex, \S is an escape sequence on its own, so to escape it you need another \ on the front. Which means you need \\\ when you are setting the original regex variable:
Perl:
use strict;
use warnings;

my $string = 'words AUTH\SYS words';
print "\$string = \"$string\"\n";

my $regex = 'AUTH\\\SYS';
print "\$regex = \"$regex\"\n";

print "matched!\n" if ($string =~ /$regex/);

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
I wouldn't use double or single quotes to quote a regular expression. That's what 'qr' is for:
Code:
my $string = 'words AUTH\SYS words';
my $regxp = qr/.*AUTH\\SYS.*/;

print "OK" if ($string =~ /$regxp/);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top