Hemanth's Scribes

ruby

Regular Expression Negation in Ruby

Author Photo

Hemanth HM

Thumbnail

We all know the pattern matching operator =~:

“hemanth” =~ /heman/ # Does match

But what about !=~? No errors, but always returns true:

"hemanth" !=~ /foo/  # => true
"hemanth" !=~ /bar/  # => true

# That's because it's parsed as:
"hemanth".!=(~/heman/)  # != is Object class, ~ is from R.E.

The Right Way: Use !~

"hemanth" !~ /heman/  # => false
"hemanth" !~ /foo/    # => true

Or use the match method:

!“hemanth”.match(“foo”) # => true

#ruby#regex
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.