正则表达式命名捕获字符串中的多个数字

时间:2011-08-16 02:57:53

标签: c# regex

给定一个字符串

 var testData = "1234 test string 987 more test";

我希望能够使用正则表达式来提取1234和987.据我所知,

 var reg = new Regex(@"?<numbers>\d+");

应该做我想要的但是当我说

 var match = reg.match(testData);

我会认为

 Assert.AreEqual(match.Groups["numbers"].Captures.Count(), 2);

但它只有1.我做错了什么?直觉告诉我

 ?<group> 

表示只能有0或1个这些值。我不应该使用命名组吗?

 *<group> 

似乎在Visual Studio中的正则表达式构建器中不起作用,但我没有在我的测试中尝试它。

2 个答案:

答案 0 :(得分:2)

为什么不使用如下的模式字符串:

Regex reg = new Regex(@"\d+");

然后通过以下方式获取数字:

MatchCollection matches = reg.Matches(testData);

之后,matches变量包含2个匹配值,表示 1234 987

您还将断言用作:

Assert.AreEqual(matches.Count, 2);

希望它会对你有所帮助!

答案 1 :(得分:-1)

try {
    Regex regexObj = new Regex(@"([\d]+)", RegexOptions.IgnoreCase);
    Match matchResults = regexObj.Match(subjectString);
    while (matchResults.Success) {
        for (int i = 1; i < matchResults.Groups.Count; i++) {
            Group groupObj = matchResults.Groups[i];
            if (groupObj.Success) {
                // matched text: groupObj.Value
                // match start: groupObj.Index
                // match length: groupObj.Length
            } 
        }
        matchResults = matchResults.NextMatch();
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}