2012-10-30 55 views
0

我为了变换像正则表达式解析

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

我试图{[^}]+}但这个表达式,我不仅是我在测试和重新标签有正在寻找一个正则表达式。有没有办法来完成这个正则表达式?

+1

正则表达式只匹配模式。它不会更改字符串。你喜欢用什么语言? –

+0

我正在使用Objective-C。 – seb

回答

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来确保结束标记包含与开始标记相同的单词。然后,您将在捕获1中找到该标签的名称以及捕获的标签值/内容2。从这里你可以用这些你想做的任何事情(例如,将这些值重新组合)。

请注意,如果您希望标签跨越多行,则应使用SINGLELINEDOTALL选项。

+0

事实上,我使用这个正则表达式来获取HTML代码中的HTML标签中的< div >和< p >之间的所有文本。我试图用< and >替换{和},它不起作用。一个主意? – seb

+0

@seb您的标签是否包含属性?你使用'SINGLELINE'还是'DOTALL'选项(我不知道如何在Objective C中设置,不好意思)。另外,如果您正在解析HTML,请**使用DOM解析器代替。 –

+0

是的,我的标签有时包含属性。 – seb