今天的第二个问题!
我想在 C# 中使用正则表达式获取包含在括号(左括号及其右括号)之间的文本。 我使用这个正则表达式:
@"\{\{(.*)\}\}
举个例子: 如果我的文字是:
text {{text{{anothertext}}text{{andanothertext}}text}} and text.
我想得到:
{{text{{anothertext}}text{{andanothertext}}text}}
但是使用这个正则表达式我得到:
{{text{{anothertext}}
我知道另一种获取文本的解决方案,但是否有使用正则表达式的解决方案?
最佳答案
幸运的是,.NET 的正则表达式引擎支持 balancing group definitions 形式的递归。 :
Regex regexObj = new Regex(
@"\{\{ # Match {{
(?> # Then either match (possessively):
(?: # the following group which matches
(?!\{\{|\}\}) # (but only if we're not at the start of {{ or }})
. # any character
)+ # once or more
| # or
\{\{ (?<Depth>) # {{ (and increase the braces counter)
| # or
\}\} (?<-Depth>) # }} (and decrease the braces counter).
)* # Repeat as needed.
(?(Depth)(?!)) # Assert that the braces counter is at zero.
\}} # Then match a closing parenthesis.",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
关于c# - 如何使用正则表达式获取包含在括号之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19389495/