简体   繁体   中英

Regex multiple capture groups on same pattern

Lets say I have a string:

12345678

I also have the following patterns:

/^.*$/
/^[0-9]+$/

Both of these patterns match the string. I want to find out that both patterns match the string. I can loop through each pattern and throw in a preg_match but this is too slow.

I want to be able to do something like this:

preg_match_all('/^(?P<pattern1>.*)|(?P<pattern2>[0-9]+)$/', $string, $matches);

This however would give me something like:

[
    'pattern1' => '12345678',
    'pattern2' => ''
]

As you can see, pattern2 comes up empty because pattern 1 has already captured the string.

How would I write my preg_match_all regex so that both pattern1 and pattern2 (and any other patterns) have a chance at matching the same string? However, I am not after a regex rule that will return all patterns if only all patterns match. I want it to return all patterns that do match and all patterns that do not.

edit

Just to further clarify,

The patterns I have given as examples, are just examples.

In my actual scenario, there will be an unknown number of patterns which match unknown strings.

The reason looping through a foreach is too slow is because I will be looping through dozens of patterns with thousands of strings. I can speed up this part of the code by how many patterns there are if they can be combined effectively into one rule per string.

You can use the following trick:

^(?P<pattern1>(?P<pattern2>^[0-9]+$)|.*)$

Since pattern2 is inside pattern1 and separated by | .. each character is checked for both the matches..

See DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM