Does Ruby regular expression have a not match operator like "!~" in Perl?

RubyRegex

Ruby Problem Overview


I just want to know whether ruby regex has a not match operator just like !~ in perl. I feel it's inconvenient to use (?!xxx)or (?<!xxxx) because you cannot use regex patterns in the xxx part.

Ruby Solutions


Solution 1 - Ruby

Yes: !~ works just fine – you probably thought it wouldn’t because it’s missing from the documentation page of Regexp. Nevertheless, it works:

irb(main):001:0> 'x' !~ /x/
=> false
irb(main):002:0> 'x' !~ /y/
=> true

Solution 2 - Ruby

AFAIK (?!xxx) is supported:

2.1.5 :021 > 'abc1234' =~ /^abc/
 => 0
2.1.5 :022 > 'def1234' =~ /^abc/
 => nil
2.1.5 :023 > 'abc1234' =~ /^(?!abc)/
 => nil
2.1.5 :024 > 'def1234' =~ /^(?!abc)/
 => 0

Solution 3 - Ruby

Back in perl, 'foobar' !~ /bar/ was perfectly perlish to test that the string doesn't contain "bar".

In Ruby, particularly with a modern style guide, I think a more explicit solution is more conventional and easy to understand:

input = 'foobar'

do_something unless input.match?(/bar/) 

needs_bar = !input.match?(/bar/)

That said, I think it would be spiffy if there was a .no_match? method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1793091View Question on Stackoverflow
Solution 1 - RubyKonrad RudolphView Answer on Stackoverflow
Solution 2 - RubycalfzhouView Answer on Stackoverflow
Solution 3 - RubyDavid HempyView Answer on Stackoverflow