加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么这个ruby代码不比正则表达式?

发布时间:2020-12-17 01:55:21 所属栏目:百科 来源:网络整理
导读:if string == /s{1,}/ or string == /n{1,}/ puts "emptiness..."end 解决方法 要针对正则表达式测试字符串,您可以执行以下五种操作中的任何一项: 1:使用String#match: ' '.match /s{1,}/ # = #MatchData:0x118ca58'f'.match /s{1,}/ # = nil 2:使用
if string == /s{1,}/ or string == /n{1,}/
  puts "emptiness..."
end

解决方法

要针对正则表达式测试字符串,您可以执行以下五种操作中的任何一项:

1:使用String#match:

' '.match /s{1,}/    # => #<MatchData:0x118ca58>
'f'.match /s{1,}/    # => nil

2:使用正则表达式匹配:

/s{1,}/.match ' '    # => <MatchData:0x11857e4>
/s{1,}/.match 'f'    # => nil

3:使用String#=?:

' ' =~ /s{1,}/       # => 0
'f' =~ /s{1,}/       # => nil

4:使用正则表达式#=?:

/s{1,}/ =~ ' '       # => 0
/s{1,}/ =~ 'f'       # => nil

5:使用正则表达式#===(这是在case语句中使用的):

/s{1,}/ === ' '      # => true
/s{1,}/ === 'f'      # => false

注意:字符串#===不能满足您的需求:

' ' === /s{1,}/      # => false
'f' === /s{1,}/      # => false

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读