我试着剪断一根线,但遇到了麻烦。
在rails中,我有一个很长的字符串,在其中,类似这样的事情发生了3-6次:
bunchofotherstringstuffandcharacters"hisquote":"The most important aspect of the painting was the treatment of lighting.","lp":andthenalotmorestringandcharacters我想要切开“这幅画最重要的方面是对光线的处理”,以及他的引述和lp之间的其他实例。
它前面的"hisquote“对于我想要的字符串是唯一的,后面的.","lp也是
如何取回这两个标识符之间的字符串的所有实例?
发布于 2012-12-10 05:06:16
所以是这样的吗?我假设您的分隔符:和,在整个字符串中都是一致的,并且使用双引号"来括起所需的字符串。
# 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"]
endhttps://stackoverflow.com/questions/13791245
复制相似问题