正则表达式:只匹配一次 [英] Regex: Matching exactly one occurrence
本文介绍了正则表达式:只匹配一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个正则表达式来精确匹配一个花括号对:
I need a regex that matches exactly one occurrence of a curly brace pair:
myString_{1-10} -> match
myString_{hello}_xyz -> match
myString_{1-10}_{hello} -> do not match
这是我的正则表达式:
(\{)[^}]*(\})
问题是我的正则表达式还匹配包含多个大括号对的字符串......我错过了什么?
The problem is that my regex also matches strings containing more than one occurrence of curly brace pairs... what am I missing?
推荐答案
你可以使用这个:
^[^{}]*\{[^}]*\}[^{}]*$
说明:
^[^{}]* // 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 [{}]
您也需要处理嵌套的大括号或不匹配的大括号
You need to take care of nested braces or unmatched braces too
这篇关于正则表达式:只匹配一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文