C#中的递归正则表达式

时间:2011-12-08 11:56:18

标签: c# .net regex

我正在用C#练习正则表达式。这是我的代码:

string test =
    "this is whole new line, with different parameters 10.1.2.1, 10.1.5.1, 10.1.3.1";
string a = Regex.Match(test, "10.[0-9].[0-9]+.[0-9]+").Value;
Console.WriteLine(a);

结果是 10.1.2.1 。它找到了第一场比赛,就是这样。

如何递归执行此功能?我是否需要添加一些额外的代码,或者是否有一个正则表达式类,它具有内置函数(我更喜欢)?

2 个答案:

答案 0 :(得分:10)

您使用Match方法明确要求只进行一次匹配。您应该使用Matches代替,并迭代结果:

string test = "this is whole new line, with different parameters 10.1.2.1, 10.1.5.1, 10.1.3.1";
foreach(Match result in Regex.Matches(test, "10.[0-9].[0-9]+.[0-9]+"))
{
    Console.WriteLine(result);  
}

该代码将打印以下内容:

10.1.2.1
10.1.5.1
10.1.3.1

答案 1 :(得分:1)

来自RegEx.Match()的文档:

  

在指定的输入字符串中搜索第一次出现的   正则表达式在Regex构造函数中指定。

它完全应该做的,返回第一场比赛。如果您想要所有匹配项,则应使用RegEx.Matches(string, string)