tags:

views:

69

answers:

3

I'm really getting my butt kicked here. I can not figure out how to write a search and replace that will properly find this string.

String:

$QData{"OrigFrom"} $Text{"wrote"}:

Note: That is the actual STRING. Those are NOT variables. I didn't write it.

I need to replace that string with nothing. I've tried escaping the $, {, and }. I've tried all kinds of combinations but it just can't get it right.

Someone out there feel like taking a stab at it?

Thanks!

+3  A: 

I originally thought that wrapping your regex in \Q/\E (the quotemeta start and end escapes) would be all that you needed to do, but it turns out that $ (and @) are not allowed inside \Q...\E sequences (see http://search.cpan.org/perldoc/perlre#Escape_sequences).

So what you need to do is escape the $ characters separately, but you can wrap everything else in \Q ... \E:

/\$\QQData{"OrigFrom"} \E\$\QText{"wrote"}:\E/
mobrule
The last `\E` is optional. The end of the regex will also mark the end of the quotemeta sequence.
mobrule
Looks like a good soultion for the OP's problem, so $string = '$QData{"OrigFrom"} $Text{"wrote"}:'; while(<>){$_ =~ s/\Q$tring//g;} will work.
Mike
quotemeta() doesn't have the same restriction as \Q. You said it but didn't use it :)
brian d foy
+1  A: 

regex using escape character \ would be

s/\$QData\{"OrigFrom"\} \$Text\{"wrote"\}://;

full test code:

#!/sw/bin/perl     

$_='$QData{"OrigFrom"} $Text{"wrote"}:';

s/\$QData\{"OrigFrom"\} \$Text\{"wrote"\}://;

print $_."\n";

outputs nothing but newline.

Mimisbrunnr
+4  A: 

No one likes quotemeta? Let Perl figure it out so you don't strain you eyes with all those backslashes. :)

 my $string = 'abc $QData{"OrigFrom"} $Text{"wrote"}: def';
 my $escaped = quotemeta '$QData{"OrigFrom"} $Text{"wrote"}:';

 $string =~ s/$escaped/Ponies!/;

 print $string;
brian d foy