Why aren't these non-capturing regex groups wo

2019-06-24 01:46发布

问题:

So I spent a lot of time on another stack overflow question, and the same problem came up with a previous one. Non-capturing groups aren't working as I'd expect them to, or so I believe.

This is a silly example along the lines of someone else's CSS test string...

Here's my regex:

(?:(rgb\([^)]*\)|\S+)(?:[ ]+)?)*

And here's the test string:

1px solid rgb(255, 255, 255) test rgb(255, 255, 255)

I'm expecting match groups of "1px","solid", "rgb(255, 255, 255)", "test", "rgb(255, 255, 255)"

But I'm only getting the last token matched.

This is the link for testing:

http://regex101.com/r/pK1uG7

What's going wrong here? I thought I had non-capturing groups down, and the way it's explained at the bottom of regex101 makes sense, including the "greediness".

回答1:

The capture group overrides each previous match. Capture group #1 first matches "1px", then capture group #1 matches "solid" overwriting "1px", then it matches "rgb(255, 255, 255)" overwriting "solid", etc.



回答2:

For this you would want to use the global option:

/(rgb\([^)]+\)|\S+)/g

http://regex101.com/r/kF2uV4

Non-capturing groups eliminate their results from the groups. So if you want to match:

"1px","solid", "rgb(255, 255, 255)", "test", "rgb(255, 255, 255)"

Then you don't want to use capturing groups that way.

See: What is a non-capturing group? What does a question mark followed by a colon (?:) mean?

See the answer of Ricardo Nolde at the top. You're eliminating the ones you say you want back.