Match对象包含组,您需要使用Match.Groups
而不是捕获获取捕获的文本。见MSDN Regex.Match
reference:
因为一场比赛可能涉及多个捕获组,Match
有Groups
属性,返回GroupCollection
。 Match
实例本身等效于集合中的第一个对象,位于Match.Groups[0]
(在Visual Basic中为Match.Groups(0)
),该对象表示整个匹配项。
你
var matches = Regex.Matches("abcde", "(?:ab(c))(d)").Cast<Match>().ToList();
取这样的:
如下您可以访问你的价值观:
var first_c= matches[0].Groups[1].Value;
var first_d= matches[0].Groups[2].Value;
使用命名捕获将使您能够访问它们Ť他道:
var matches = Regex.Matches("abcde", "(?:ab(?<myc>c))(?<myd>d)").Cast<Match>().ToList();
var first_c= matches[0].Groups["myc"].Value;
var first_d= matches[0].Groups["myd"].Value;
看到这个答案http://stackoverflow.com/questions/15170279/regex-with-non-capturing-group-in-c-sharp也许你会发现这里的东西的http://计算器.com/questions/906493/how-do-i-access-named-capturing-groups-in-a-net-regex – SergeyAn
谢谢我检查过它们,但它们却完全相反。当正则表达式捕获他们的组时,这些人很高兴。我的问题是matches1 [0] .Captures [0] .Value捕获整个“abcd”的东西。它应该只分别给我“c”和“d” – doker
第一组(组0)_always_指的是输入字符串。匹配的组从1开始。 –