开发者

How do I write this regex to replace a string in perl?

If the string begins with ^abc,don't modify it.otherwise append abc to the beginning of it.

I know i开发者_如何转开发t can be done by 2 steps:m// and s//,but I want to do it in a single s/../ in perl.


s/^(?!\^abc)/abc/

does the trick, although

$_ = 'abc'.$_ if !/^\^abc/;

might be clearer.


>perl -E"$_=$ARGV[0]; s/^(?!\^abc)/abc/; say;" "^abcdef"
^abcdef

>perl -E"$_=$ARGV[0]; s/^(?!\^abc)/abc/; say;" "defghi"
abcdefghi

>perl -E"$_=$ARGV[0]; $_ = 'abc'.$_ if !/^\^abc/; say;" "^abcdef"
^abcdef

>perl -E"$_=$ARGV[0]; $_ = 'abc'.$_ if !/^\^abc/; say;" "defghi"
abcdefghi
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜