为什么这些非捕获正则表达式组不能正常工作?

时间:2021-05-24 12:16:00

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...

这是一个愚蠢的例子,沿着别人的CSS测试字符串......

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)"

我期待匹配组“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".

这里出了什么问题?我以为我有非捕获组,并且它在regex101底部的解释方式是有道理的,包括“贪婪”。

2 个解决方案

#1


3  

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.

捕获组会覆盖每个先前的匹配。捕获组#1首先匹配“1px”,然后捕获组#1匹配“solid”覆盖“1px”,然后匹配“rgb(255,255,255)”覆盖“solid”等。

#2


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.

请参阅顶部的Ricardo Nolde的答案。你正在消除你想要的那些。

#1


3  

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.

捕获组会覆盖每个先前的匹配。捕获组#1首先匹配“1px”,然后捕获组#1匹配“solid”覆盖“1px”,然后匹配“rgb(255,255,255)”覆盖“solid”等。

#2


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.

请参阅顶部的Ricardo Nolde的答案。你正在消除你想要的那些。