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

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

概述鉴于字符: strs = [ "foo", " ", "Hello \n there", " Ooh, leading and trailing space! ",] 我想要一个简单的方法,按顺序识别所有连续的空白和非空白字符的运行,以及运行是否是空格: strs.each{ |str| p find_whitespace_runs(str) }#=> [ {k:1, 鉴于字符串:

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}  endend

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

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

以上是内存溢出为你收集整理的ruby – 识别空格与其他字符在字符串中运行全部内容,希望文章能够帮你解决ruby – 识别空格与其他字符在字符串中运行所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1294405.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存