正则表达式捕获组提前终止

时间:2014-08-18 11:15:00

标签: c# .net regex

我通常不会问愚蠢的正则表达式问题。但这是正则秃鹫的一个......

拿这些字符串......

-This is nice (show cow)
*This (or that) (show mouse)
-Whatever
-Hiya (everyone)

所有这些都应该是匹配的。即带有*-的引导,然后是任何文本,然后可以有条件地跟随空白和(show xxx),其中xxx可以是任何文本。我希望这些分开捕获,即......

-This is nice (show cow)
   Match 1 : 'This is nice'
   Match 2 : '(show cow)' or just 'cow'

*This (or that) (show mouse)
   Match 1 : 'This (or that)'
   Match 2 : 'show mouse' or just 'mouse'

-Whatever
   Match 1 : 'Whatever'

-Hiya (everyone)
   Match 1 : 'Hiya (everyone)'

+Hello
   No Match

我尝试过各种各样......

[\-*](.+?)(\s+\(show (.+)\))?
    Terminates early and only captures 1 char of match 1

[\-*](.+)(\s+\(show (.+)\))?
    Terminates late and captures all of the text as match 1 including `(show....`

[\-*](.+)(\s+\(show (.+)\)$)?
    As above

我确定这应该很简单!我不想在第1场比赛中否定(show - 因为我想允许这样,例如-Hello (show a) (show b),其中第1场比赛是Hello (show a)而第2场比赛是{{1} }(或只是(show b)

1 个答案:

答案 0 :(得分:4)

我想你想要这样的东西,

^[-*](.*?)(?: \(show\s*([^)]*)\)|$)

DEMO