Ruby 正则表达式是否有一个类似 Perl 中的“ ! ~”的不匹配运算符?

我只想知道 ruby regex 是否有一个不匹配操作符,就像 perl 中的 !~一样。我觉得使用 (?!xxx)(?<!xxxx)不方便,因为在 xxx部分不能使用正则表达式模式。

51683 次浏览

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

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

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.