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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex special chars in interpolated variables

Status
Not open for further replies.

domster

Programmer
Oct 23, 2003
30
GB
Hi, I'm hoping someone out there can save me the bother of searching through the manuals. Is there any way of telling Perl not to treat reserved characters (+, * etc) as special when they occur in interpolateed variables? For example, I had an array of various codes, some of which began with a +, and I was running through the array, looking for each in a string:

while ($i < $#codearray) {
$code = $codearray[$i];
if ($stringtosearch =~ s/^(\s*)$gramcode//) {
...
last;
}
$i++;
}

I couldn't work out for ages why the codes beginning with + weren't getting found, then I realised Perl was treating them as sepcial characters. I converted the + to \+ in the codes, but is there a better way of doing it? Thanks,

Dom
 
Yep! I actually asked this very same question a few weeks ago. Use /Q and /E within the regexp; it treats $variables as variables, but treats any regexp syntax within those strings literally:

Code:
my $string = 'I got an A+ in school today!';
if(/\Q$string\E/) {
  print "String matches.";
} else {
  print "String doesn't match.";
}

HTH,

Nick
 
Yep, use \Q and \E. See man perlre for more.
Example:
Code:
#!/usr/bin/perl -w
my $pat = ".*a+";
my @strings = qw( .*a+ fffaa );
## wrong
foreach $string (@strings) {
    print "$string matches $pat\n" if $string =~ m/$pat/;
}
## right
foreach $string (@strings) {
    print "$string matches $pat\n" if $string =~ m/\Q$pat\E/;
}
Cheers, Neil
 
\Q and \E - of course, silly me! Thanks both for the very fast response.

Dom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top