Reputation: 4500
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:
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".
Upvotes: 4
Views: 321
Reputation: 1401
For this you would want to use the global option:
/(rgb\([^)]+\)|\S+)/g
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.
Upvotes: 2
Reputation: 427
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.
Upvotes: 3