Fastest way to check if a string matches a regexp in ruby?

前端 未结 7 1491
独厮守ぢ
独厮守ぢ 2020-12-13 05:07

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

My problem is that I have to \"egrep\" through a huge list of strings to find whic

7条回答
  •  暖寄归人
    2020-12-13 05:49

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

    pattern.match?(string)
    

    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?
    Added Regexp#match?, which executes a regexp match without creating a back reference object and changing $~ to reduce object allocation.

提交回复
热议问题