我为了变换像正则表达式解析
{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
来确保结束标记包含与开始标记相同的单词。然后,您将在捕获1
中找到该标签的名称以及捕获的标签值/内容2
。从这里你可以用这些你想做的任何事情(例如,将这些值重新组合)。
请注意,如果您希望标签跨越多行,则应使用SINGLELINE
或DOTALL
选项。
正则表达式只匹配模式。它不会更改字符串。你喜欢用什么语言? –
我正在使用Objective-C。 – seb