如何在括号内查找正则表达式中的一些例外情况?

All*_*Liu 10 ruby regex

我有一个正则表达式/^\[(text:\s*.+?\s*)\]/mi,目前可用于捕获以括号开头的文本text:.这是一个有效的例子:

[text: here is my text that is
captured within the brackets.]
Run Code Online (Sandbox Code Playgroud)

现在,我想添加一个异常,以便它允许某些括号,如下例所示:

[text: here is my text that is
captured within the brackets
and also include ![](/some/path)]
Run Code Online (Sandbox Code Playgroud)

基本上,我需要它来允许![](/some/path)匹配中的括号.

任何帮助将不胜感激.谢谢.

更新:

以下是括号内的文本应匹配的一些情况:

[text: here is my text that is
captured within the brackets
and also include ![](/some/path)]

[text: here is my text that is
captured within the brackets
and also include ![](/some/path) and some more text]

[text: ![](/some/path)]

![text: cat]
Run Code Online (Sandbox Code Playgroud)

以下是一些不匹配的情况:

[text: here is my text that is
captured within the brackets
and also include ![invalid syntax](/some/path)]

[text: here is my text that is
captured within the brackets
and also include ![] (/some/path)]

[text: here is my text that is
captured within the brackets
and also include ! [](/some/path)]

[text: here is my text that is
captured within the brackets
and also include ! [] (/some/path)]
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 6

好的,所以你想要允许

  • 一个不是括号或字符的字符
  • 序列 ![]

在起始和结束括号之间.这给你正则表达式

/^\[(text:[^\[\]]*(?:!\[\][^\[\]]*)*)\]/mi
Run Code Online (Sandbox Code Playgroud)

说明:

^           # Start of line
\[          # Match [
(           # Start of capturing group
 text:      # Match text:
 [^\[\]]*   # Match any number of characters except [ or ]
 (?:        # Optional non-capturing group:
  !\[\]     #  Match ![]
  [^\[\]]*  #  Match any number of characters except [ or ]
 )*         # Repeat as needed (0 times is OK)
)           # End of capturing group
\]          # Match ]
Run Code Online (Sandbox Code Playgroud)

在regex101.com上测试它.