【发布时间】:2012-11-25 09:29:32
【问题描述】:
我只想知道 ruby 正则表达式是否有不匹配运算符,就像 perl 中的!~。我觉得使用 (?!xxx) 或 (?<!xxxx) 很不方便,因为您不能在 xxx 部分使用正则表达式模式。
【问题讨论】:
我只想知道 ruby 正则表达式是否有不匹配运算符,就像 perl 中的!~。我觉得使用 (?!xxx) 或 (?<!xxxx) 很不方便,因为您不能在 xxx 部分使用正则表达式模式。
【问题讨论】:
是的:!~ 工作得很好——你可能认为它不会因为it’s missing from the documentation page of Regexp。尽管如此,它仍然有效:
irb(main):001:0> 'x' !~ /x/
=> false
irb(main):002:0> 'x' !~ /y/
=> true
【讨论】:
!~ 记录在 Object 下。
RegExp#match?,您可以轻松地否定它。根据release notes,它比!~进行的分配更少
支持 AFAIK (?!xxx):
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
【讨论】:
回到 perl,'foobar' !~ /bar/ 非常适合测试字符串不包含“bar”。
在 Ruby 中,尤其是现代风格指南,我认为更明确的解决方案更传统且易于理解:
input = 'foobar'
do_something unless input.match?(/bar/)
needs_bar = !input.match?(/bar/)
也就是说,我认为如果有一个.no_match? 方法会很漂亮。
【讨论】: