gpt4 book ai didi

java - Java Matcher.find 和 Matcher.group 的 C#/.NET 等效项

转载 作者:行者123 更新时间:2023-11-30 07:23:34 25 4
gpt4 key购买 nike

我看到有一些关于 Java Matcher 类的帖子,但我找不到关于特定方法 find()group() 的帖子.

我有这段代码,其中 Lane 和 IllegalLaneException 已经定义:

private int getIdFromLane(Lane lane) throws IllegalLaneException {
Matcher m = pattern.matcher(lane.getID());
if (m.find()) {
return Integer.parseInt(m.group());
} else {
throw new IllegalLaneException();
}
}

查看 Java 文档,我们有以下内容:

find() - 尝试查找输入序列中与模式匹配的下一个子序列。

group() - 返回与前一个匹配项匹配的输入子序列。

我的问题是,这相当于 C# 中的 find()group() 方法?

编辑:我忘了说我正在将 MatchCollection 类与 Regex 一起使用

C# 代码:

private static Regex pattern = new Regex("\\d+$"); // variable outside the method

private int getIdFromLane(Lane lane) //throws IllegalLaneException
{
MatchCollection m = pattern.Matches(lane.getID());
...
}

最佳答案

在 C# 上,您将使用正则表达式。 Regex 类有一个名为“Matches”的函数,它将返回模式的所有重合匹配。

每个匹配都有一个名为“组”的属性,其中存储捕获的组。

所以,找到 -> Regex.Matches,组 -> Match.Groups。

它们不是直接等效的,但它们将为您提供相同的功能。

这是一个简单的例子:

var reg = new Regex("(\\d+)$");

var matches = reg.Matches("some string 0123");

List<string> found = new List<string>();

if(matches != null)
{
foreach(Match m in matches)
found.Add(m.Groups[1].Value);
}

//do whatever you want with found

请记住,m.Groups[0] 将包含完整捕获,任何后续组都将成为捕获组。

另外,如果您只期望一个结果,那么您可以使用 .Match:

var match = reg.Match("some string 0123");

if(match != null && match.Success)
//Process the Groups as you wish.

关于java - Java Matcher.find 和 Matcher.group 的 C#/.NET 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37136376/

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