Ruby 识别字符串中的空白与其他字符运行
鉴于这些条件:Ruby 识别字符串中的空白与其他字符运行,ruby,regex,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:" "} ], #=&
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
现实世界的动机:在未执行的代码中区分空白和非空白的写作。这是可行的,但我不喜欢出现
,除非是空的?
(和紧凑的)
我会很高兴地投票给任何能产生正确结果的答案,并会接受任何更优雅或明显更有效的答案。出于好奇,为什么要用0/1而不是falsy/truthy?@WayneConrad,主要是因为它使第三个示例结果适合一行:)此外,如问题链接所示,实际上,我正在调用每个并将其索引到一个标签数组中。很棘手!在提交之前,我想测试一下,但我认为你赢得了金星奖。是的,这是正确的,速度与我当前基于拆分的黑客一样快。(而且在记忆力方面可能会稍微好一点。)干得好。完美,perfetto,冻糕,perfekt,perfecto,完ぺき, 完美, 완전한 !
def find_whitespace_runs(str)
str.scan(/((\s+)|(\S+))/).map { |full, ws, nws|
{ :k => nws ? 1 : 0, :s => full }
}
end
def find_whitespace_runs(str)
str.scan(/((\s+)|(\S+))/).map { |full, ws, nws|
{ :k => nws ? 1 : 0, :s => full }
}
end