Learning
Learning

Reputation: 219

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 it can be done by 2 steps:m// and s//,but I want to do it in a single s/../ in perl.

Upvotes: 1

Views: 103

Answers (1)

ikegami
ikegami

Reputation: 386646

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

Upvotes: 2

Related Questions