Page 1 of 1

Regex works without, but not with lookbehind assertion

Posted: Thu Jan 08, 2009 6:42 am
by undercover
Hi, I try to find all occurences of ", " thats comma followed by a whitespace which are in between {...}. E.g.

"I like your {car, house, cat, forum} a lot, but I don't like commas in parentheses.

It would be easy find and replace if there weren't any commas outside of the brackets which I don't want to find (and replace). I tried this PHP script with regex and it finds me "{car, " what is correct.

Code: Select all

$lines = file ('test.txt');
foreach ($lines as $line_num => $line) {
    $suchmuster = '#{[\w\s]+,\s#';    //'#(?<={[\w\s]+),\s(?=\w+|})#';
        $ersetzung = '|';
        //echo preg_replace($suchmuster, $ersetzung, $line);
        preg_match($suchmuster, $line, $treffer);
        echo $treffer[0]."<br>";
}
If I try to look behind the "{car" and only get the ", " with this little change

Code: Select all

$lines = file ('test.txt');
foreach ($lines as $line_num => $line) {
    $suchmuster = '#{(?<=[\w\s]+),\s#';    //'#(?<={[\w\s]+),\s(?=\w+|})#';
        $ersetzung = '|';
        //echo preg_replace($suchmuster, $ersetzung, $line);
        preg_match($suchmuster, $line, $treffer);
        echo $treffer[0]."<br>";
}
I dont get any results anymore. Would anybody help me out and tell me whats wrong with my lookbehind assertion? Thank you very much!

Re: Regex works without, but not with lookbehind assertion

Posted: Thu Jan 08, 2009 6:48 am
by prometheuzz
undercover wrote:...

I dont get any results anymore. Would anybody help me out and tell me whats wrong with my lookbehind assertion? Thank you very much!
PHP does not support variable length look behinds, that's why it doesn't work.
You will need to do something like this (untested!):

Code: Select all

$text = "I like your {car, house, cat, forum} a lot, but I don't like commas in parentheses.";
$replacement = '@';
echo preg_replace('/,\s*(?=[^{}]*})/i', $replacement, $text);
 

Re: Regex works without, but not with lookbehind assertion

Posted: Thu Jan 08, 2009 8:44 am
by undercover
Thank you very much for this quick and helpful answer. I don't understand this expression completely by now, but it works perfectly.

Re: Regex works without, but not with lookbehind assertion

Posted: Thu Jan 08, 2009 8:50 am
by prometheuzz
undercover wrote:Thank you very much for this quick and helpful answer. I don't understand this expression completely by now, but it works perfectly.
No problem. Play around with it a bit and if doesn't sink in after that, feel free to ask for clarification.