SKing
SKing

Reputation: 3

How to escape a string that looks like a regular expression in Perl

I have a script that, among other things, searches a list of text files to replace a Windows path (text string) with another path.

The problem is that some of the folder names begin with a number and a dash. Perl seems to think that I am trying to invoke a regular expression here. I get the message, "Reference to nonexistent group in regex".

the string looks like this:

\\\BAGlobal\6-Engineering\3-Tech

I have quoted it like this:

 my $find = "\\\\\\\BAGlobal\\\6-Engineering\\\3-Tech"

How do I escape the 6- and 3- ?

Upvotes: 0

Views: 148

Answers (1)

simbabque
simbabque

Reputation: 54323

The problem is not the the dash in 6- but all the backslashes \.

It thinks that \3 and \6 are back-references to previously matched groups, like /foo(bar) foo\1/ would match the string foobar foobar.

If you use this in a pattern match you need to either include \Q and \E to add quoting, or apply the quotemeta built-in to your $find.

my $find = '\\\\\\\BAGlobal\\\6-Engineering\\\3-Tech';

$string =~ m/\Q$find\E/;

Or with quotemeta.

my $find = quotemeta '\\\\\\\BAGlobal\\\6-Engineering\\\3-Tech';

$string =~ m/$find/;

Also see perlre.

Note that your example code is probably wrong. The number of backslashes you have there is uneven, and double quotes "" interpolate, so each pair of backslashes \\ turn into one actual backslash in the string. But because you have 7 of them, the last one is seen as the escape for B, turning that into \B, which is not a valid escape sequence. I used single quotes '' in my code above.

Upvotes: 5

Related Questions