如何匹配第一对方括号内的所有内容

How to match everything inside the first pair of square brackets

我正在尝试创建 regular expression in sieve. The implementation of sieve that I'm using is Dovecot Pigeonhole

我订阅了 github 项目更新,我收到来自 github 的电子邮件,其主题格式如下:

Re: [Opserver] Create issues on Jira from Exception details page (#77)

主题行中方括号中包含一个项目名称。这是我的筛选脚本的相关部分:

if address "From" "notifications@github.com" {
  if header :regex "subject" "\[(.*)\]" {
      set :lower :upperfirst "repository" "";
      fileinto :create "Subscribtions.GitHub.${repository}"; stop;
  } else {
      fileinto :create "Subscribtions.GitHub"; stop;
  }
}

正如您从上面看到的,我正在将邮件移动到适当的项目 IMAP 文件夹中。所以带有上述主题的消息将在 Subscribtions.Github.Opserver

中结束

不幸的是,这个脚本有一个小问题。如果有人在 github 问题的标题中添加方括号,过滤器就会中断。例如,如果主题是:

[Project] [Please look at it] - very weird issue

上面的过滤器会将邮件移动到文件夹 Subscribtions.Github.Project] [please look at it,这是完全不可取的。无论如何,我希望将其移至 Subscribtions.Github.Project

发生这种情况是因为默认情况下正则表达式是贪婪的。所以他们匹配最长的可能匹配。然而,当我尝试以通常的方式修复它时,将 "\[(.*)\]" 更改为 "\[(.*?)\]" 似乎没有任何改变。

如何编写此正则表达式以使其按预期运行?

答案是把"\[(.*)\]"改成"\[([^]]*)\]"

通过阅读regex spec linked in the question we disvover that POSIX regular expression are used. Unfortunately those do not support non-greedy matches

但是,在上面给出的这种特殊情况下,有一个解决方法。