greediness in sed

2020-03-31 07:07发布

问题:

I want

ereg ($rat, $dog, $cat)

to become

preg_match ('#'.$rat.'#', $dog, $cat)

To achieve this, I did

echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg\(.*\)(\(.*\),/preg_match\1('#'.\2.'#',/g"

but, this regex changed the

ereg ($rat, $dog, $cat)

into

preg_match ('#'.$rat, $dog.'#', $cat)

instead of

preg_match ('#'.$rat.'#', $dog, $cat)

Can someone help me to build a regex that changes

ereg ($rat, $dog, $cat)

into

preg_match ('#'.$rat.'#', $dog, $cat)

回答1:

Just exclude ','...

echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg\(.*\)(\([^,]*\),/preg_match\1('#'.\2.'#',/g"


回答2:

Note: This also works if you have multiple instances of ereg ($rat, $dog, $cat) on the same line whereas other answers do not:

$ echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg\([^(]*\)(\([^,]*\),\([^)]*)\)/preg_match\1('#'.\2.'#',\3/g"
preg_match ('#'.$rat.'#', $dog, $cat)

Example

$ echo 'ereg ($rat, $dog, $cat) ereg ($rat, $dog, $cat)' | sed "s/ereg\([^(]*\)(\([^,]*\),\([^)]*)\)/preg_match\1('#'.\2.'#',\3/g"
preg_match ('#'.$rat.'#', $dog, $cat) preg_match ('#'.$rat.'#', $dog, $cat)


回答3:

~ ross$ echo 'ereg ($rat, $dog, $cat)' | sed -e "s/.*(\([^,]*\),\([^,]*\),\([^)]*\))/preg_match ('#'.\1.'#', \2, \3)/"
preg_match ('#'.$rat.'#',  $dog,  $cat)


回答4:

How about:

$ echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg *(\([^,]*\), \([^,]*\)\([^)]*\))/preg_match('#'.\1.'#', \2\3)/g"
preg_match('#'.$rat.'#', $dog, $cat)


回答5:

I rather like Perl regexs (easier to write):

echo 'ereg ($rat, $dog, $cat)' | perl -pe 's/ereg\s*\(\s*(\$[^,]+),(.+)\)/preg_match("#" . $1 . "#", $2)/g'

or better (for PHP):

echo 'ereg ($rat, $dog, $cat)' | perl -pe 's/ereg\s*\(\s*(\$[^,]+),(.+)\)/preg_match("#{$1}#", $2)/g'

In sed, it would be:

echo 'ereg ($rat, $dog, $cat)' | sed -e 's/ereg\s*(\s*\(\$[^,]\+\),\(.\+\))/preg_match("#" . \1 . "#", \2)/'

Too many backslashes!!!