← Back to Ruby Operators

Regex Match Operator

The regex match operator (=~) is used to match a string against a regular expression.

The form of this that you are probably looking for is Regexp#=~ which checks if the given string matches the regex.

> simple_email = /\A.+@.+\z/
=> /\A.+@.+\z/
> simple_email =~ 'taco'
=> nil
> simple_email =~ '[email protected]'
=> 0

Note: Regexp#=~ is not strictly interchangeable with String#=~. In the case of Named Captures, for instance, the two will behave differently. The Ruby docs give us this example to demonstrate that:

> number= nil
=> nil
> "no. 9" =~ /(?<number>\d+)/
=> 4
> number # => nil (not assigned)
=> nil
> /(?<number>\d+)/ =~ "no. 9"
=> 4
> number #=> "9"
=> "9"

See the Regexp docs for more details about everything you can do with Regexp.

Bonus: check out Regex's Free-Spacing Mode.