简体   繁体   English

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

[英]Regex capturing group terminating early

I don't usually ask dumb regex questions. 我通常不问愚蠢的正则表达式问题。 But here's one for the regex vultures.... 但这是一个用于正则表达式的秃鹰。

Take these strings... 拿这些弦...

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

All these should be a match. 所有这些都应该匹配。 ie Lead with * or - , then any text, then can conditionally be followed by whitespace and (show xxx) where xxx can be any text. 即以*-开头,然后是任何文本,然后可以有条件地后面跟空格和(show xxx) ,其中xxx可以是任何文本。 I want these captured separately ie... 我希望将这些单独捕获,即...

-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

I have tried variously... 我尝试了各种...

[\-*](.+?)(\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

I'm sure this should be really easy! 我相信这应该真的很简单! I don't want to go with negating (show within Match 1 - as I would like to permit this eg -Hello (show a) (show b) where Match 1 is Hello (show a) and Match 2 is (show b) (or just b ) 我不想进行否定(show在Match 1中(show -如我所愿,例如-Hello (show a) (show b) ,其中Match 1是Hello (show a)而Match 2是(show b) (或只是b

I think you want something like this, 我想你想要这样的东西

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

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM