strange problem with groups

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
madrazel
Forum Newbie
Posts: 7
Joined: Wed Sep 09, 2009 9:24 am

strange problem with groups

Post 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.
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: strange problem with groups

Post 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?
madrazel
Forum Newbie
Posts: 7
Joined: Wed Sep 09, 2009 9:24 am

Re: strange problem with groups

Post 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'
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: strange problem with groups

Post 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.
madrazel
Forum Newbie
Posts: 7
Joined: Wed Sep 09, 2009 9:24 am

Re: strange problem with groups

Post by madrazel »

So how to tell to the inner group so it check all values of its or statement before going up ?
Post Reply