c# - 在C#中匹配varName $ [index]和@varName [index](正则表达式帮助)

标签 c# regex

在此字符串中:

"lorem$ dolor @sit ipsum amet$[consectetuer$[5]] @adipiscing[@elit[3]]"


我要符合以下条件:


lorem$ 
@sit
amet$[consectetur$[5]]
@adipiscing[@elit[3]]



我的表情几乎差一点了,但是由于某种原因,我不太理解。这是我现在的测试程序。这是我到目前为止的内容:

Regex varEx = new Regex(@"(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?)\]|[\W\D\s])");

string test = "lorem$ dolor @sit ipsum amet$[consectetuer$[5]] @adipiscing[@elit[3]]";

foreach (Match m in varEx.Matches(test)) {
     Console.WriteLine("{0,10}  {1}", "Match:", m.Value);
     Console.WriteLine("{0,10}  {1}", "Variable:", m.Groups["Variable"].Value);
     Console.WriteLine("{0,10}  {1}", "Index:", m.Groups["Index"].Value);
     Console.WriteLine();
}


程序输出以下内容:


   Match:  lorem$
Variable:  lorem$
   Index:

   Match:  @sit
Variable:  @sit
   Index:

   Match:  amet$[consectetuer$[5]
Variable:  amet$
   Index:  consectetuer$[5

   Match:  @adipiscing[@elit[3]
Variable:  @adipiscing
   Index:  @elit[3



几乎是对的!最后两场比赛只剩下最后一位。我究竟做错了什么?

最佳答案

您只需设置为捕获]的其中一个

您需要向]命名组中添加另一个终止Index来捕获它

更改此:

(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?)\]|[\W\D\s])


对此:

(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?\]+)\]|[\W\D\s])


test

关于c# - 在C#中匹配varName $ [index]和@varName [index](正则表达式帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27515643/

相关文章:

c# - 不能明确指定标识列,但也不能不指定

java - 我可以在正则表达式中声明优先于匹配项吗?

regex - 检查两个模式是否相互匹配?

python - (正则表达式)如何在python中删除引号和里面的内容?

regex - 获取 R 中每列的最后四个单词

c# - moq 模拟对象与实际类有多少相似之处?

c# - 使用 X509 证书为多个收件人进行 XML 加密和解密

c# - ToCharArray 函数无法正常工作

c# - 如何让NBuilder在生成对象时拦截getter?

用于去除 XML 标签的 Java 正则表达式不起作用