2014-12-01 66 views
0

我需要我的正则表达式来接受这个:Ruby Regexp麻烦。如何接受一个字符串,只有当它没有“富”

"add chain=input comment="test" protocol=icmp blah blah other stuff" 

,但不能接受这一点:

"add chain=input comment="test" blah blah disabled=yes 

所以基本上,如果在的结束字符串说,禁用=是,不匹配它。 我试过这个:

(add action=drop chain=input .*(?!disabled=yes)) 
add action=drop chain=input [^disabled=yes] 
add action=drop chain=input.*[^(disabled=yes)] 

和其他一些变化,但无济于事。我做错了什么?


编辑:

def check(line, key) 
    return line[ key ] ? true : false 
end 

check("add action=drop chain=input comment="test" disabled=yes", /add action=drop chain=input.*[^(disabled=yes)]/) 

这是一些代码,只是打破。

+0

向我们展示您使用的确切正则表达式,而不仅仅是字符串等效项。 – 2014-12-01 22:45:46

回答

2

使用如下所示的基于负面lookahead的正则表达式。

^(?!.*disabled=yes$)add(?: action=drop)? chain=input.* 

Rubular

(?!.*disabled=yes$)负先行断言,没有一个字符串disabled=yes会出现在最后。而且我也将这个action=drop字符串设置为可选,因为我没有在你的输入字符串中找到它,而是在你的正则表达式中。

+0

谢谢!我知道必须有一个简单的正则表达式解决方案。 – Schylar 2014-12-01 23:54:26

+0

很高兴解决。别客气。 – 2014-12-01 23:55:25

-1

为什么要使用正则表达式?

[ 
    'add chain=input comment="test" protocol=icmp blah blah other stuff', 
    'add chain=input comment="test" blah blah disabled=yes' 
].reject{ |s| s.end_with?('disabled=yes') } # => ["add chain=input comment=\"test\" protocol=icmp blah blah other stuff"] 

end_with?大约为2x比等效的正则表达式模式更快。

require 'fruity' 

compare do 
    _end_with { 'foo'.end_with?('o') } 
    regexp { 'foo'[/o$/] } 
end 
# >> Running each test 32768 times. Test will take about 1 second. 
# >> _end_with is faster than regexp by 2x ± 0.1 (results differ: true vs o) 

正火的输出,使他们只匹配使用模式将放缓:

require 'fruity' 

compare do 
    _end_with { 'foo'.end_with?('o') } 
    regexp { !!'foo'[/o$/] } 
end 
# >> Running each test 32768 times. Test will take about 1 second. 
# >> _end_with is faster than regexp by 2.4x ± 0.1 

如果你只是HAVE使用模式,这通常是值得商榷的,用一个简单的模式来拒绝你不想第一个字符串,所以你剩下的那些你做的:

[ 
    'add chain=input comment="test" protocol=icmp blah blah other stuff', 
    'add chain=input comment="test" blah blah disabled=yes' 
].reject{ |s| s[/disabled=yes$/] } # => ["add chain=input comment=\"test\" protocol=icmp blah blah other stuff"] 

模式越复杂,出问题了,它会发生泄漏,导致误报。相反,尽可能保持简单。

如果你真的以使其不可读,加装线路噪声^ H^H^H^H^H^H^H^^ h^^ H ^哈使用负前瞻:

'blah blah other stuff'[/^((?!disabled=yes).)+$/] # => "blah blah other stuff" 
'blah blah disabled=yes'[/^((?!disabled=yes).)+$/] # => nil 
+0

这将意味着更改检查方法。这意味着要修改100多个元素的正则表达式阵列 – Schylar 2014-12-01 22:51:26

+1

也许,通过展示您正在尝试做的更好的示例,我们可以帮助您完全避免该问题? – 2014-12-01 22:53:18

+0

难以想象的正则表达式吗? – Schylar 2014-12-01 22:55:22