我需要一个正则表达式,匹配恰好出现一次花括号对:
myString_{1-10} -> match
myString_{hello}_xyz -> match
myString_{1-10}_{hello} -> do not match
这是我的正则表达式:
(\{)[^}]*(\})
问题在于我的正则表达式也匹配包含多个花括号对的字符串…我错过了什么?
我需要一个正则表达式,匹配恰好出现一次花括号对:
myString_{1-10} -> match
myString_{hello}_xyz -> match
myString_{1-10}_{hello} -> do not match
这是我的正则表达式:
(\{)[^}]*(\})
^[^{}]*\{[^}]*\}[^{}]*$
说明:
^[^{}]* // 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
。 - Rohit Jain^[^{}]*(\{([^}]*)\})[^{}]*$
。现在,第1组
包含花括号,第2组
包含不带花括号的内容。 - Rohit Jain(?<=^(?>[^{\n]*))\{[^}]*\}(?=[^{\n]*$)
(\{.*?\})_*(?:\{)*
输出将包含您要查找的内容。
这需要使用“s”标志 // 点匹配所有。
myString_}{}
或myString_{}_{
。 - SheetJS