开发者

How can I search and replace text that looks like Perl variables?

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 nothin开发者_StackOverflowg. 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!


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;


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/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜