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
精彩评论