gpt4 book ai didi

c# - C# 中的递归正则表达式

转载 作者:行者123 更新时间:2023-11-30 19:12:12 27 4
gpt4 key购买 nike

我正在用 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

关于c# - C# 中的递归正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8430669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com