简体   繁体   English

C#中的递归正则表达式

[英]Recursive regular expression in C#

I am practicing regex with C#. 我正在用C#练习正则表达式。 This is my code: 这是我的代码:

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);

The result is 10.1.2.1 . 结果是10.1.2.1 It finds the first match and that's it. 它找到第一场比赛就是这样。

How can I perform this function recursively ? 如何递归执行此功能? Do I need to add some extra code or is there a regex class which has this as a built in function (which I would prefer)? 我是否需要添加一些额外的代码,或者是否有一个正则表达式类,它具有内置函数(我更喜欢)?

You are explicitly asking for only one match, using the Match method. 您使用Match方法明确要求只匹配一个匹配项。 You should use Matches instead, and iterate over the result: 您应该使用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);  
}

That code will print the following: 该代码将打印以下内容:

10.1.2.1
10.1.5.1
10.1.3.1

From the documentation of RegEx.Match() : RegEx.Match()的文档:

Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. 在指定的输入字符串中搜索Regex构造函数中指定的第一次出现的正则表达式。

It does exactly what it should, returns the first match. 它完全应该做的,返回第一场比赛。 If you want all matches you should use RegEx.Matches(string, string) . 如果你想要所有匹配,你应该使用RegEx.Matches(string, string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM