0

次のようなものを変換するために正規表現を探しています

{test}hello world{/test} and {again}i'm coming back{/again} in hello world i'm coming back. 

試してみ{[^}]+}ましたが、この正規表現では、テストにあるものだけをタグ付けすることはできません。この正規表現を完成させる方法はありますか?

4

1 に答える 1

1

これを適切に行うことは、通常、正規表現の機能を超えています。ただし、これらのタグがネストされないこと、および入力にタグを示さない中括弧が含まれないことを保証できる場合は、この正規表現で照合を行うことができます。

\{([^}]+)}(.*?)\{/\1}

説明:

\{        # a literal {
(         # capture the tag name
[^}]+)    # everything until the end of the tag (you already had this)
}         # a literal }
(         # capture the tag's value
.*?)      # any characters, but as few as possible to complete the match
          # note that the ? makes the repetition ungreedy, which is important if
          # you have the same tag twice or more in a string
\{        # a literal {
\1        # use the tag's name again (capture no. 1)
}         # a literal }

したがって、これは後方参照\1を使用して、終了タグに開始タグと同じ単語が含まれていることを確認します。次に、captureにタグの名前があり、capture1にタグの値/コンテンツがあり2ます。ここから、これらを好きなように操作できます(たとえば、値を元に戻します)。

タグを複数の行にまたがる場合は、SINGLELINEまたはオプションを使用する必要があることに注意してください。DOTALL

于 2012-10-31T00:01:33.043 に答える