可选捕获始终被忽略,以支持*

时间:2014-05-07 18:31:46

标签: regex

鉴于声明

the cat and the dog played together

我可以用这个正则表达式捕捉猫和狗

(cat).*(dog)

句子中不会总是有猫,所以我将第一个捕获组设为可选

(cat)?.*(dog)

使用可选捕获组时,.*总是抓取整个第一部分,忽略可选捕获,即使它在那里。如果猫在那里怎么可能被抓住,但如果它不存在,正则表达式仍将匹配狗?

我试过让明星不贪婪

(cat)?.*?(dog)

并尝试使用|而不是可选的捕获组,但第一个捕获组始终被忽略。

示例结果http://regex101.com/r/pR1kZ9

2 个答案:

答案 0 :(得分:2)

(?:(cat).*)?(dog)

匹配'cat'和后续角色直到下一个'dog'作为单个非捕获组,但捕获'cat'。

http://regex101.com/r/cE9yC8

演示

示例:

the cat and the dog played together  - match 'cat' and 'dog
the mouse didn't play with the dog   - match 'dog'

答案 1 :(得分:1)

我找到了一个:

(?:.*?(?=cat))?(cat)?.*(dog)

将所有内容与cat一词相匹配;然后匹配猫,如果它在那里,然后匹配任何东西到狗。

the cat played with the dog    ==> 'cat', 'dog'
the mouse played with the dog  ==> 'dog'
the dog played with the cat    ==> 'dog'

演示:http://regex101.com/r/eT7pR4