Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 用于解析的正则表达式_Objective C_Regex_Nsregularexpression - Fatal编程技术网

Objective c 用于解析的正则表达式

Objective c 用于解析的正则表达式,objective-c,regex,nsregularexpression,Objective C,Regex,Nsregularexpression,我正在寻找一个正则表达式,以便转换如下内容 {test}hello world{/test} and {again}i'm coming back{/again} in hello world i'm coming back. 我尝试了{[^}]+},但是使用这个正则表达式,我不能只拥有test和repeal标记中的内容。有没有办法完成这个正则表达式?正确地完成这个正则表达式通常超出了正则表达式的能力。但是,如果您可以保证这些标记永远不会嵌套,并且您的输入永远不会包含不表示标记的花括号,那么

我正在寻找一个正则表达式,以便转换如下内容

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

我尝试了
{[^}]+}
,但是使用这个正则表达式,我不能只拥有test和repeal标记中的内容。有没有办法完成这个正则表达式?

正确地完成这个正则表达式通常超出了正则表达式的能力。但是,如果您可以保证这些标记永远不会嵌套,并且您的输入永远不会包含不表示标记的花括号,那么此正则表达式可以进行匹配:

\{([^}]+)}(.*?)\{/\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
1
中找到标签的名称,在capture
2
中找到标签的值/内容。从这里,您可以随心所欲地使用这些值(例如,将这些值重新组合在一起)


请注意,如果希望标记跨越多行,则应使用
单线
点调用
选项。

Regex仅匹配模式。它不会改变字符串。您喜欢使用哪种语言?事实上,我使用这个正则表达式是为了在HTML代码中获得
和HTML标记之间的所有文本。我试图用替换{and},但它不起作用。。想法?@seb您的标签是否包含属性?您是否使用
SINGLELINE
DOTALL
选项(对不起,我不知道如何在目标C中设置)。另外,如果您正在解析HTML,请改用DOM解析器。是的,我的标记有时包含属性。这与您当时的问题有很大不同(因为这个正则表达式也会尝试在结束标记中查找所有这些属性)。您可能正在寻找类似的内容,然后:
]+)[^>]*>(.*)
。但是,还是要查看一些DOM解析器。