0

我正在尝试分割字符串并遇到麻烦。

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

bunchofotherstringstuffandcharacters"hisquote":"The most important aspect of the painting was the treatment of lighting.","lp":andthenalotmorestringandcharacters

我想删掉“这幅画最重要的方面是灯光的处理。”,以及其他介于他的引用和 lp 之间的实例。

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

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

4

1 回答 1

0

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

# 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
于 2012-12-09T21:06:15.813 回答