开发者

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

开发者 https://www.devze.com 2023-03-15 16:17 出处:网络
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 per

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

精彩评论

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