首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在rails中选择字符串的多个部分

在rails中选择字符串的多个部分
EN

Stack Overflow用户
提问于 2012-12-10 04:05:12
回答 1查看 139关注 0票数 0

我试着剪断一根线,但遇到了麻烦。

在rails中,我有一个很长的字符串,在其中,类似这样的事情发生了3-6次:

代码语言:javascript
运行
复制
bunchofotherstringstuffandcharacters"hisquote":"The most important aspect of the painting was the treatment of lighting.","lp":andthenalotmorestringandcharacters

我想要切开“这幅画最重要的方面是对光线的处理”,以及他的引述和lp之间的其他实例。

它前面的"hisquote“对于我想要的字符串是唯一的,后面的.","lp也是

如何取回这两个标识符之间的字符串的所有实例?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-10 05:06:16

所以是这样的吗?我假设您的分隔符:,在整个字符串中都是一致的,并且使用双引号"来括起所需的字符串。

代码语言:javascript
运行
复制
# escape double quotes
longstring = %q(bunchofotherstringstuffandcharacters"hisquote":"The most important aspect of the painting was the treatment of lighting.","lp":andthenalotmorestringandcharacters)

# split on double quotes
substrings = longstring.split("\"").to_enum

# somewhere to sure the strings you want
save = []

# use a rescue clause to detect that the enumerator 'substrings' as reached an end
begin
    while true do
        remember = substrings.next
        case substrings.peek # lets see if that next element is our deliminator
        when ":" # Once the semicolon is spotted ahead, grab the three strings we want.
            save << remember
            substrings.next # skip the ":"
            save << substrings.next
            substrings.next # skip the ","
            save << substrings.next
        end
    end
rescue StopIteration => e
    puts "End of Substring Enumeration was reached."
ensure
    puts save.inspect   #=>  ["hisquote", "The most important aspect of the painting was the treatment of lighting.", "lp"]
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13791245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档