识别空格和其他字符在字符串中运行



给定字符串:

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:" "},
#=>   {k:1, s:"leading"},
#=>   {k:0, s:" "},
#=>   {k:1, s:"and"},
#=>   {k:0, s:" "},
#=>   {k:1, s:"trailing"},
#=>   {k:0, s:" "},
#=>   {k:1, s:"space!"},
#=>   {k:0, 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

真实的动机:编写一个语法高亮标记来区分空白和非空白,否则未加前缀的代码

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

这可以工作,但是我不喜欢unless empty?(和compact)的存在。

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

我很乐意为任何产生正确结果的答案投票,并将接受任何更优雅或明显更有效的答案。

最新更新