November 4, 2016
This blog is part of our Ruby 2.4 series.
Ruby has many ways to match with a regular expression.
It returns true/false and sets the $~ global variable.
/stat/ === "case statements"
#=> true
$~
#=> #<MatchData "stat">
It returns integer position it matched or nil if no match. It also sets the $~ global variable.
/stat/ =~ "case statements"
#=> 5
$~
#=> #<MatchData "stat">
It returns match data and also sets the $~ global variable.
/stat/.match("case statements")
#=> #<MatchData "stat">
$~
#=> #<MatchData "stat">
This new method just returns true/false and does not set any global variables.
/case/.match?("case statements")
#=> true
So Regexp#match?
is good option when we are only concerned with the fact that
regex matches or not.
Regexp#match?
is also faster than its counterparts as it reduces object
allocation by not creating a back reference and changing $~
.
require 'benchmark/ips'
Benchmark.ips do |bench|
EMAIL_ADDR = '[email protected]'
EMAIL_REGEXP_DEVISE = /\A[^@\s]+@([^@\s]+\.)+[^@\W]+\z/
bench.report('Regexp#===') do
EMAIL_REGEXP_DEVISE === EMAIL_ADDR
end
bench.report('Regexp#=~') do
EMAIL_REGEXP_DEVISE =~ EMAIL_ADDR
end
bench.report('Regexp#match') do
EMAIL_REGEXP_DEVISE.match(EMAIL_ADDR)
end
bench.report('Regexp#match?') do
EMAIL_REGEXP_DEVISE.match?(EMAIL_ADDR)
end
bench.compare!
end
#=> Warming up --------------------------------------
#=> Regexp#=== 103.876k i/100ms
#=> Regexp#=~ 105.843k i/100ms
#=> Regexp#match 58.980k i/100ms
#=> Regexp#match? 107.287k i/100ms
#=> Calculating -------------------------------------
#=> Regexp#=== 1.335M (± 9.5%) i/s - 6.648M in 5.038568s
#=> Regexp#=~ 1.369M (± 6.7%) i/s - 6.880M in 5.049481s
#=> Regexp#match 709.152k (± 5.4%) i/s - 3.539M in 5.005514s
#=> Regexp#match? 1.543M (± 4.6%) i/s - 7.725M in 5.018696s
#=>
#=> Comparison:
#=> Regexp#match?: 1542589.9 i/s
#=> Regexp#=~: 1369421.3 i/s - 1.13x slower
#=> Regexp#===: 1335450.3 i/s - 1.16x slower
#=> Regexp#match: 709151.7 i/s - 2.18x slower
If this blog was helpful, check out our full blog archive.