c#RegEx只显示一次捕获

时间:2014-01-31 15:54:57

标签: c# regex

private String pattern = @"^{(.*)|(.*)}$";
ret = groups[0].Captures.Count.ToString(); // returns 1

是不是应该返回2次捕获?因为我的RegExp中有两个()

我的字符串例如:

{test1 | test2}

第一次捕获应该是test1和secnd test2,但我得到整个字符串作为回报,捕获计数是1为什么会这样?

更新

     Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
     MatchCollection matches = rgx.Matches(_sourceString);
     String ret = "";
     foreach (Match match in matches)
     {
         GroupCollection groups = match.Groups;
         ret = groups[0].Captures[0].Value;
     }

     return ret; //returns the whole string, but I've expected 'test1'

1 个答案:

答案 0 :(得分:5)

|在正则表达式中具有特殊含义。 A|B匹配AB

要按字面意思匹配|,您需要逃避它:

@"^{(.*)\|(.*)}$";