ruby - 如何通过正则表达式查找括号内的文本,但有一些异常(exception)?

标签 ruby regex

我有一个正则表达式 /^\[(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/

相关文章:

ruby - GitLab 设置问题与 bundle

php - 从电视节目文件名中提取名称、季节和剧集

JavaScript - 检查给定的子字符串是否被字母包围

javascript - Jquery .replace 使浏览器崩溃

python - Python 的 re.compile 需要与 re.search 不同的语法吗?

java - PHP 正则表达式 到 Java 正则表达式

ruby - 数组包含 x 和其他

Ruby 深度哈希循环?

ruby-on-rails - Ruby on Rails使用命令行 ``计算图像的md5

ruby-on-rails - 另一个语句中的每个语句都出现故障?