正则表达式:恰好匹配一次

时间:2013-07-28 21:37:04

标签: regex

我需要一个正好匹配一个大括号对的正则表达式:

myString_{1-10}         -> match
myString_{hello}_xyz    -> match
myString_{1-10}_{hello} -> do not match

这是我的正则表达式:

(\{)[^}]*(\})

问题是我的正则表达式还匹配包含多个大括号对的字符串...我缺少什么?

3 个答案:

答案 0 :(得分:2)

您可以使用:

^[^{}]*\{[^}]*\}[^{}]*$

说明:

^[^{}]*    // Match 0 or more occurrences of character other than [{}]
 \{        // Match a `{`
 [^}]*     // Match 0 or more occurrences of character other than }
 \}        // Match a `}`
 [^{}]*$   // Match 0 or more occurrences of character other than [{}]

您还需要处理嵌套大括号或不匹配的大括号

答案 1 :(得分:0)

如果你正在使用包含所有三行的整个变量,那么这就是你要找的东西:

(\{.*?\})_*(?:\{)*

输出将包含您正在寻找的内容。

这需要“s”标志//点匹配所有。

答案 2 :(得分:0)

您可以使用多线模式在.net中使用此模式:

(?<=^(?>[^{\n]*))\{[^}]*\}(?=[^{\n]*$)