0

文字列をスライスしようとしていますが、問題が発生しています。

レールでは、非常に長いストリングがあり、その中で、次のようなことが3〜6回発生します。

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

「絵画の最も重要な側面は照明の扱いでした。」と、hisquoteとlpの間にある他の例も切り取りたいと思います。

その前にある「hisquote」は、私が欲しい弦に固有のものであり、その後にある。 "、"lpも同様です。

これら2つの識別子の間の文字列のすべてのインスタンスを取り戻すにはどうすればよいですか?

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 に答える