2016-04-28 9 views
0

私はテスト文字列を持っています:ネストされたタグの一致した出現数

s = "A test [[you|n|note|content of the note with a [[link|n|link|http://link]] inside]] paragraph. wef [[you|n|note|content of the note with a [[link|n|link|http://link]] inside]] test"です。

文字列の[[...]]部分の出現と一致する必要があります。文字列中にネストされた[[ ]]タグの第2レベルまでが可能です(テスト文字列に示されています)。

私は/\[\[.*?\]\]/を始め、それは唯一の次に一致します。 [[you|n|note|content of the note with a [[link|n|link|http://link]](それは]]の最後の発生を欠けている

私は、各[[ .. ]]ブロックの残りの部分に一致する行くにはどうすればよいの正規表現でこれは可能ですか? ?

+0

外側のもののみが必要ですか?内部に単一の '['または ']'がありますか? – sawa

+1

あなたの例として望ましい結果は何ですか? –

答えて

1

あなたが単一の孤立[または]を持っていない場合、それはかなり単純です。以下は、ネストされたレベルに制限を負いません。

s.scan(/(?<match>\[\[(?:[^\[\]]|\g<match>)*\]\])/).flatten 

リターン:

[ 
    "[[you|n|note|content of the note with a [[link|n|link|http://link]] inside]]", 
    "[[you|n|note|content of the note with a [[link|n|link|http://link]] inside]]" 
] 
+0

ありがとう@さわ!それはうまくいく。さて、私はこの正規表現を使用し、別のものと組み合わせる必要があります。テキストの変更に合わせる必要があるという要件があります。 デフォルトでは、私は '/ \ s /'とマッチしているので、各変更を単語として扱います。私はこれを修正して、「単語のすべての変更、[[..]] 'ブロックを単語全体として扱うようにする必要があります。 '[" A "、" test "、[[you | n | note | [[link | n | link | http://]の付いたノートの内容は以下の通りです:string.split(regex)/link]] inside]] "、" paragraph。 "]'。 これは可能ですか? – Sean

1

はここで非正規表現のソリューションです。私は左(右)括弧が常にペアで現れると仮定しました。

level = 0 
s.each_char.each_cons(2).with_index.with_object([]) do |(pair, i), a| 
    case pair.join 
    when "[[" 
    level += 1 
    a << i if level==1 
    when "]]" 
    a << i+1 if level==1 
    level -= 1 
    end 
end.each_slice(2).map { |b,e| s[b..e] } 
    #=> ["[[you|n|note|content of the note with a [[link|n|link|http://link]] inside]]", 
    # "[[you|n|note|content of the note with a [[link|n|link|http://link]] inside]]"] 
関連する問題