4

我有一个来自配置文件的片段,我需要能够匹配指定的字符串引用内容,但只有当它们没有被注释掉时,这是我当前的正则表达式:

(?<!=#)test\.this\.regex\s+\"(.*?)\"

我觉得这应该工作?我是这样读的:

(?<!=#)向后看以确保它前面没有#

test\.this\.regex\s+\"(.*?)\"火柴test.this.regex "sup1"

这是配置片段

    test.this.regex "sup1" hi |sup1| # test.this.regex "sup3" hi |sup3|
# test.this.regex "sup2" do |sup2|
    test.this.regex "sup2" do |sup2|

但我的正则表达式匹配所有 4 次:

Match 1
1.  sup1
Match 2
1.  sup3
Match 3
1.  sup2
Match 4
1.  sup2
4

2 回答 2

0

您可以使用这个 PCRE 正则表达式:

/(?># *(*SKIP)(*FAIL)|(?:^|\s))test\.this\.regex\s+\"[^"]*\"/

工作演示

  • (*FAIL)表现得像一个失败的否定断言,是(?!)
  • (*SKIP)定义一个点,当子模式稍后失败时,正则表达式引擎不允许回溯
  • (*SKIP)(*FAIL)一起提供了一个很好的限制替代方案,您不能在上面的正则表达式中使用可变长度的lookbehinf。

更新:不确定 ruby​​ 是否支持(*SKIP)(*FAIL),所以给出这个替代版本:

(?:# *test\.this\.regex\s+\"[^"]*\"|\b(test\.this\.regex\s+\"[^"]*\"))

并寻找非空匹配组#1。

工作演示 2

于 2014-05-17T05:24:08.677 回答
0

如果您的问题体现在第一句话中(而不是专门关于外观),您为什么不直接使用String#split和您的正则表达式而不是后视?

def doit(str)
  r = /test\.this\.regex\s+\"(.*?)\"/
  str.split('#').first[r,1]
end

doit('test.this.regex "sup1" hi |sup1| # test.this.regex "sup3" hi |sup3|')
  #=> "sup1"
doit('# test.this.regex "sup2" do |sup2|')
  #=> nil
doit('test.this.regex "sup2" do |sup2|')
  #=> "sup2"
于 2014-05-17T19:01:40.917 回答