次のようなものを変換するために正規表現を探しています
{test}hello world{/test} and {again}i'm coming back{/again} in hello world i'm coming back.
試してみ{[^}]+}
ましたが、この正規表現では、テストにあるものだけをタグ付けすることはできません。この正規表現を完成させる方法はありますか?
次のようなものを変換するために正規表現を探しています
{test}hello world{/test} and {again}i'm coming back{/again} in hello world i'm coming back.
試してみ{[^}]+}
ましたが、この正規表現では、テストにあるものだけをタグ付けすることはできません。この正規表現を完成させる方法はありますか?
これを適切に行うことは、通常、正規表現の機能を超えています。ただし、これらのタグがネストされないこと、および入力にタグを示さない中括弧が含まれないことを保証できる場合は、この正規表現で照合を行うことができます。
\{([^}]+)}(.*?)\{/\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