Regex捕获组提前终止

本文关键字:终止 Regex | 更新日期: 2023-09-27 18:18:23

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

取这些字符串…

-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是(show b)(或只是b)

Regex捕获组提前终止

我想你需要这样的东西,

^[-*](.*?)(?: '(show's*([^)]*)')|$)
演示