Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Matcher.find和Matcher.group的C#/.NET等效项_Java_C#_Matcher - Fatal编程技术网

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

Java Matcher.find和Matcher.group的C#/.NET等效项,java,c#,matcher,Java,C#,Matcher,我已经看到了一些关于Java Matcher类的帖子,但是我没有找到关于特定方法find()和group()的帖子 我有一段代码,其中已经定义了Lane和IllegalLaneException: private int getIdFromLane(Lane lane) throws IllegalLaneException { Matcher m = pattern.matcher(lane.getID()); if (m.find()) { return In

我已经看到了一些关于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类

C#代码:

在C#上,您将使用正则表达式。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

嗯,好吧,我想我误解了正则表达式的含义。一开始是匹配!但是,如果Regex.Matches为null,我如何处理它?这通常意味着根本没有匹配项。让我举一个例子。另外,如果您只希望得到一个结果,您可以使用.Match,它将只返回一个匹配,您可以检查它的.Success属性以检查它是否匹配。
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
var match = reg.Match("some string 0123");

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