Why does this regex run differently in sed than in Perl/Ruby?

Viewed 984

I have a regex that gives me one result in sed but another in Perl (and Ruby).

I have the string one;two;;three and I want to highlight the substrings delimited by the ;. So I do the following in Perl:

$a = "one;two;;three";
$a =~ s/([^;]*)/[\1]/g;
print $a;

(Or, in Ruby: print "one;two;;three".gsub(/([^;]*)/, "[\\1]").)

The result is:

[one][];[two][];[];[three][]

(I know the reason for the spurious empty substrings.)

Curiously, when I run the same regexp in sed I get a different result. I run:

echo "one;two;;three" | sed -e 's/[^;]*/[\0]/g'

and I get:

[one];[two];[];[three]

What is the reason for this different result?

EDIT:

Somebody replied "because sed is not perl". I know that. The reason I'm asking my question is because I don't understand how sed copes so well with zero-length matches.

3 Answers
Related