if string == /\s{1,}/ or string == /\n{1,}/
puts "emptiness..."
end
最佳答案
要针对 Regex
测试 String
,您可以执行以下五项操作中的任何一项:
1:使用String#match
:
' '.match /\s{1,}/ # => #<MatchData:0x118ca58>
'f'.match /\s{1,}/ # => nil
2:使用Regex#match
:
/\s{1,}/.match ' ' # => <MatchData:0x11857e4>
/\s{1,}/.match 'f' # => nil
3:使用String#=~
:
' ' =~ /\s{1,}/ # => 0
'f' =~ /\s{1,}/ # => nil
4:使用Regex#=~
:
/\s{1,}/ =~ ' ' # => 0
/\s{1,}/ =~ 'f' # => nil
5:使用 Regex#===
(这是在 case
语句中使用的):
/\s{1,}/ === ' ' # => true
/\s{1,}/ === 'f' # => false
注意:String#===
不会做你想做的事:
' ' === /\s{1,}/ # => false
'f' === /\s{1,}/ # => false
关于ruby - 为什么这个 ruby 代码不比较正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2353931/