检查字符串是否与 ruby​​ 中的正则表达式匹配的最快方法? [英] Fastest way to check if a string matches a regexp in ruby?

查看:63
本文介绍了检查字符串是否与 ruby​​ 中的正则表达式匹配的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中检查字符串是否与正则表达式匹配的最快方法是什么?

What is the fastest way to check if a string matches a regular expression in Ruby?

我的问题是我必须通过一个巨大的字符串列表egrep"才能找到哪些与运行时给出的正则表达式匹配的字符串.我只关心字符串是否与正则表达式匹配,而不关心它在哪里匹配,也不关心匹配组的内容是什么.我希望这个假设可以用来减少我的代码花费匹配的时间正则表达式.

My problem is that I have to "egrep" through a huge list of strings to find which are the ones that match a regexp that is given at runtime. I only care about whether the string matches the regexp, not where it matches, nor what the content of the matching groups is. I hope this assumption can be used to reduce the amount of time my code spend matching regexps.

我用

pattern = Regexp.new(ptx).freeze

我发现 string =~ patternstring.match(pattern) 稍微快一点.

I have found that string =~ pattern is slightly faster than string.match(pattern).

是否有其他技巧或捷径可以使此测试更快?

Are there other tricks or shortcuts that can used to make this test even faster?

推荐答案

从 Ruby 2.4.0 开始,您可以使用 RegExp#match?:

Starting with Ruby 2.4.0, you may use RegExp#match?:

pattern.match?(string)

Regexp#match?2.4.0 的发行说明,因为它避免了由其他方法执行的对象分配,例如 Regexp#match=~:

Regexp#match? is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match and =~:

Regexp#match?
添加了 Regexp#match?,它在不创建反向引用对象和更改 $~ 以减少对象分配的情况下执行正则表达式匹配.

Regexp#match?
Added Regexp#match?, which executes a regexp match without creating a back reference object and changing $~ to reduce object allocation.

这篇关于检查字符串是否与 ruby​​ 中的正则表达式匹配的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆