C# / .NET equivalent for Java Matcher.find and Matcher.group

一世执手 提交于 2019-12-24 06:26:38

问题


I have seen that there are some posts regarding the Java Matcher class, but I was not able to find one regarding the specific methods find() and group().

I have this piece of code, where Lane and IllegalLaneException have already been defined:

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

Looking at the Java Documentation, we have the following:

find() - Attempts to find the next subsequence of the input sequence that matches the pattern.

group() - Returns the input subsequence matched by the previous match.

My question is, which is the equivalent to the methods find() and group() in C#?

EDIT: I forgot to say that I am using the MatchCollection class together with Regex

C# code:

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

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

回答1:


On C# you will use Regex. Regex class has a function named "Matches" which will return all coincident matches for the pattern.

And each Match has a property called Groups where are stored captured groups.

So, find -> Regex.Matches, group -> Match.Groups.

They're not direct equivalents, but they will give you the same functionality.

Here is a simple example:

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

Remember that m.Groups[0] will contain the full capture and any subsequent Group will be captured groups.

Also, if you expect just one result then you can use .Match:

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

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


来源:https://stackoverflow.com/questions/37136376/c-sharp-net-equivalent-for-java-matcher-find-and-matcher-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!