java matcher.find和matcher.group的c#/.net等价物

ldioqlga  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(295)

我看到过一些关于javamatcher类的帖子,但是我没有找到一篇关于特定方法的帖子 find() 以及 group() .
我有一段代码,其中已经定义了lane和illegalaneexception:

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() -返回与上一个匹配匹配的输入子序列。
我的问题是,哪种方法是等效的 find() 以及 group() 在c#?
edit:我忘了说我将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());
...
}
gwbalxhn

gwbalxhn1#

在c上,您将使用regex。regex类有一个名为“matches”的函数,它将返回模式的所有一致匹配。
每个匹配项都有一个名为groups的属性,其中存储的是捕获的组。
所以,find->regex.matches,group->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.

相关问题