我有一个正则表达式 /^\[(text:\s*.+?\s*)\]/mi
目前可以捕获以 text 开头的括号中的文本:
。以下是它的工作示例:
[text: here is my text that is
captured within the brackets.]
现在,我想添加一个异常(exception),以便它允许某些括号,如下例所示:
[text: here is my text that is
captured within the brackets
and also include ![](/some/path)]
基本上,我需要它允许匹配中的 ![](/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]
以下是一些不应该匹配的情况:
[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)]
最佳答案
好的,所以你想允许其中之一
- 不是括号或的字符
- 序列
![]
在开始和结束括号之间。这给你正则表达式
/^\[(text:[^\[\]]*(?:!\[\][^\[\]]*)*)\]/mi
解释:
^ # 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 ]
测试一下 live on regex101.com .
关于ruby - 如何通过正则表达式查找括号内的文本,但有一些异常(exception)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33773292/