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

前端 未结 3 1888
醉梦人生
醉梦人生 2020-12-13 03:12

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 (?

3条回答
  •  执念已碎
    2020-12-13 03:37

    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.

提交回复
热议问题