Page 1 of 1
strange problem with groups
Posted: Mon May 03, 2010 4:52 pm
by madrazel
Code: Select all
preg_match('#((?<found>a)(x|c))?#',"ab ax ac",$testresult);
- this gives nothing
but if you remove the most outward parentheses:
Code: Select all
preg_match('#(?<found>a)(x|c)#',"ab ax ac",$testresult);
Array ( [0] => ax [found] => a [1] => a [2] => x )
The problem is that if it fails on first occurence for 'a' which is ax then it gives up completely and does not bother to check the rest of the string.
I need these outward parentheses because I want preg_replace to return true even if it not finds what I look for.
Re: strange problem with groups
Posted: Mon May 03, 2010 9:59 pm
by ridgerunner
The regex is doing exactly what you are telling it to do. Since the whole regex is wrapped in a ()? structure (which is optional), it gives up if the insides don't match at the first character in the string.
It makes no sense to force the preg_match function to return TRUE if there is no match. Why do you need it to do that?
Re: strange problem with groups
Posted: Tue May 04, 2010 1:19 am
by madrazel
I want simply to force regex to try all options from inner group that is (x|c) before backtrack to outer group and do not give up on first failure.
((?<found>a)(x|c)|b) - still gives up in inner brackets and do not bother to check 'c'
Re: strange problem with groups
Posted: Tue May 04, 2010 8:18 am
by ridgerunner
((?<found>a)(x|c)|b) Does not match c because (this new and different regex) now finds b first. (assuming your test data is still "ab ax ac".)
The inner group is not giving up. It is doing exactly what you are telling it to do.
Can you try to explain the problem you are trying to solve with some more detail? I don't really understand your problem as worded.
Re: strange problem with groups
Posted: Wed May 05, 2010 5:15 am
by madrazel
So how to tell to the inner group so it check all values of its or statement before going up ?