为什么要使用正则表达式?
[
'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
向我们展示您使用的确切正则表达式,而不仅仅是字符串等效项。 – 2014-12-01 22:45:46