给定字符串:
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/