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

ruby – 识别空格与其他字符在字符串中运行

发布时间:2020-12-17 03:16:18 所属栏目:百科 来源:网络整理
导读:鉴于字符串: strs = [ "foo"," ","Hello n there"," Ooh,leading and trailing space! ",] 我想要一个简单的方法,按顺序识别所有连续的空白和非空白字符的运行,以及运行是否是空格: strs.each{ |str| p find_whitespace_runs(str) }#= [ {k:1,s:"foo"} ],
鉴于字符串:

strs = [
  "foo","    ","Hello n there"," Ooh,leading and trailing space!  ",]

我想要一个简单的方法,按顺序识别所有连续的空白和非空白字符的运行,以及运行是否是空格:

strs.each{ |str| p find_whitespace_runs(str) }
#=> [ {k:1,s:"foo"} ],#=> [ {k:0,s:"    "} ],#=> [ {k:1,s:"Hello"},{k:0,s:" n "},{k:1,s:"World"} ],#=> [
#=>   {k:0,s:" "},#=>   {k:1,s:"Ooh,"},#=>   {k:0,s:"leading"},s:"and"},s:"trailing"},s:"space!"},s:"  "},#=> ]

这几乎可以工作,但只要字符串不以空格开头,就包含一个前导{k:0,s:“”}组:

def find_whitespace_runs(str)
  str.split(/(S+)/).map.with_index do |s,i|
    {k:i%2,s:s}
  end
end

现实世界的动机:编写a syntax highlighter,将空白区域与非空白区域中的非空白区分开来.

解决方法

def find_whitespace_runs(str)
  str.scan(/((s+)|(S+))/).map { |full,ws,nws|
    { :k => nws ? 1 : 0,:s => full } 
  }
end

(编辑:李大同)

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

    推荐文章
      热点阅读