2012-08-22 183 views
1

我无法捕获字符串中的值。我只想要我不想捕获的数字T:。这个失败的测试解释为:正则表达式捕获

[TestMethod] 
public void RegExTest() 
{ 
    var rex = new Regex("^T([0-9]+):"); //as far as I understand, the() denote the capture group 
    var match = rex.Match("T12:abc"); 
    Assert.IsTrue(match.Success); 
    Assert.IsTrue(match.Groups[0].Success); 
    Assert.AreEqual("12", match.Groups[0].Captures[0]); //fails, actual is "T12:" 
} 
+0

不管你不想捕捉你必须表示它。你的正则表达式应该是'^(?: T)([0-9] +)(?:\:)$' –

+0

@AndreCalil我明白了,是的,除了必须使用Groups [1]结果。谢谢。 – weston

+0

第一组是组[1]。组[0]是整个比赛。 – Toto

回答

1

Groups集合,这是基于零,表示从索引1
Groups[0]捕获组总是表示整个匹配。
因此,您需要执行Groups[1]而不是上面的Groups[0]

的MatchGroups属性返回GroupCollection对象 包含表示捕获基团在单个 匹配组对象。集合中第一个Group对象(索引为0) 表示整个匹配。下面的每个对象代表单个捕获组的 结果。

The Group Collection

0

通过命名组得知它。

[TestMethod] 
public void RegExTest() 
{ 
    var rex = new Regex("^T(?<N>[0-9]+):"); 
    var match = rex.Match("T12:abc"); 
    Assert.IsTrue(match.Success); 
    Assert.IsTrue(match.Groups[0].Success); 
    Assert.AreEqual("12", match.Groups["N"].Value); 
} 

应该已经看过更难:How do I access named capturing groups in a .NET Regex?

+0

好吧,恭喜你回答你自己的问题。无论如何,你可以尝试一下我的建议吗? –

+0

@AndreCalil我做了,它有效,但就像我只是通过访问'Group [1]'所说的那样,实际上Kash指出了作品而不改变表达式。 – weston

1

所以你要牛逼之间不匹配的数字:

以下是一个

@"(?<=T)\d+(?=:)"//no need of groups here 

关于你的正则表达式的简单Regex

您正则表达式

^T([0-9]+): 

应该是这样的

T(\d+)://^ is not needed and [0-9] can be represented as \d 

这里

Group[0] would be T:12//a full match 
Group[1] would be 12//1st match within()i.e.1st() 
Group[2] would be //2nd match within()i.e 2nd() 
+0

谢谢,'^'是为了确保T在字符串的开头。所以我需要那个吗? – weston

+0

不,你不需要它... 如果你使用'^'然后一个字符串** sddsT55:**不匹配,因为'^'意味着你想要T在乞讨。所以一个字符串** T55: **会与'^'相匹配,但不会与** sddsT55相匹配:** – Anirudha

+0

@weston如果您确定'string'总是'T54:',那么您应该使用'^' – Anirudha