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'
答案 0 :(得分:5)
|
在正则表达式中具有特殊含义。 A|B
匹配A
或B
。
要按字面意思匹配|
,您需要逃避它:
@"^{(.*)\|(.*)}$";