---
title: "Regular Expression Negation in Ruby"
description: "The difference between !=~ and !~ for regex negation in Ruby. Practical notes and code examples on Regular Expression in JS."
url: "https://h3manth.com/scribe/regular-expression-negation-in-ruby/"
canonical_url: "https://h3manth.com/scribe/regular-expression-negation-in-ruby/"
markdown_url: "https://h3manth.com/scribe/blog/regular-expression-negation-in-ruby.md"
publishDate: "2013-04-24T00:00:00.000Z"
author: "Hemanth HM"
category: "ruby"
tags: ["ruby","regex"]
word_count: 83
reading_time_minutes: 1
x_markdown_tokens: 209
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Regular Expression Negation in Ruby

> The difference between !=~ and !~ for regex negation in Ruby. Practical notes and code examples on Regular Expression in JS.

We all know the pattern matching operator `=~`:

"hemanth" =~ /heman/  # Does match

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

```ruby
"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 `!~`

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

Or use the `match` method:

!"hemanth".match("foo")  # => true
