[英]Recursive regular expression in C#
我正在用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 。 它找到第一场比赛就是这样。
如何递归执行此功能? 我是否需要添加一些额外的代码,或者是否有一个正则表达式类,它具有内置函数(我更喜欢)?
您使用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
从RegEx.Match()
的文档:
在指定的输入字符串中搜索Regex构造函数中指定的第一次出现的正则表达式。
它完全应该做的,返回第一场比赛。 如果你想要所有匹配,你应该使用RegEx.Matches(string, string)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.