在不使用 .nil 的情况下测试正则表达式是否不匹配字符串的开头?
Test if a regexp does not match the beginning of a string without using .nil?
我正在测试一些字符串以确保它们以字母开头:
name =~ /\A[a-zA-Z].*/
但由于在 Ruby 中计算结果为 nil
或 0
并且都转换为 false,我需要进行额外的 .nil?
测试:
if(name =~ /\A[a-zA-Z].*/).nil? ...
这是正确的方法还是我遗漏了什么?
编辑:
感谢您的答复,由于我的无知,我做出了错误的假设,过度简化了示例。它应该是(注意否定):
name !=~ /\A[a-zA-Z].*/
irb(main):001:0> a = "abc"
=> "abc"
irb(main):006:0> (a !=~/\Aabc/)
=> true
irb(main):007:0> (a !=~/\Ab/)
=> true
but since in Ruby this evaluates to either nil or 0 and both cast to false
错误,只有nil
(准确地说是false
)在条件语句中被视为false
。 0
被视为 true
。所以
if name =~ /\A[a-zA-Z].*/
完全没问题。
关于您编辑的问题,您不能向任何运算符添加感叹号 (!
) 使其成为否定运算符。没有像 !=~
这样的运算符(顺便说一句,这些 'operators' 实际上是 methods),所以要实现您的目标。你应该这样做:
if !(name =~ /\A[a-zA-Z].*/)
或者您可以使用 unless
代替:
unless name =~ /\A[a-zA-Z].*/
我正在测试一些字符串以确保它们以字母开头:
name =~ /\A[a-zA-Z].*/
但由于在 Ruby 中计算结果为 nil
或 0
并且都转换为 false,我需要进行额外的 .nil?
测试:
if(name =~ /\A[a-zA-Z].*/).nil? ...
这是正确的方法还是我遗漏了什么?
编辑: 感谢您的答复,由于我的无知,我做出了错误的假设,过度简化了示例。它应该是(注意否定):
name !=~ /\A[a-zA-Z].*/
irb(main):001:0> a = "abc"
=> "abc"
irb(main):006:0> (a !=~/\Aabc/)
=> true
irb(main):007:0> (a !=~/\Ab/)
=> true
but since in Ruby this evaluates to either nil or 0 and both cast to false
错误,只有nil
(准确地说是false
)在条件语句中被视为false
。 0
被视为 true
。所以
if name =~ /\A[a-zA-Z].*/
完全没问题。
关于您编辑的问题,您不能向任何运算符添加感叹号 (!
) 使其成为否定运算符。没有像 !=~
这样的运算符(顺便说一句,这些 'operators' 实际上是 methods),所以要实现您的目标。你应该这样做:
if !(name =~ /\A[a-zA-Z].*/)
或者您可以使用 unless
代替:
unless name =~ /\A[a-zA-Z].*/