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

标签 ruby regex

给定字符串:

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

现实世界的动机:写作 a syntax highlighter区分非词法分析代码中的空白和非空白。

最佳答案

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

关于ruby - 识别空格与其他字符在字符串中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930927/

相关文章:

Python re.sub 去除引号内的前导/尾随空格

regex - 您在正则表达式中使用过 Perl 5.10 回溯控制动词吗?

JavaScript/正则表达式 : Remove text between parentheses

javascript - 在 JavaScript 中替换多个字符串的好方法

ruby-on-rails - rails/minitest 不为选择的测试加载 fixture

ruby-on-rails - 发送表单参数哈希作为响应内容

ruby - 为什么我会得到 "no implicit conversion of String into Integer (TypeError)"?

ruby-on-rails - Ruby On Rails 开发机

html - 如何在 collection_check_boxes 上将宽度设置为百分比?

双倍的正则表达式