开发者

greediness in sed

开发者 https://www.devze.com 2023-02-04 11:14 出处:网络
I want ereg ($rat, $dog, $cat) to become preg_match (\'#\'.$rat.\'#\', $dog, $cat) To achieve this, I did

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)


Just exclude ','...

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


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)


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


How about:

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


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!!!

0

精彩评论

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