javac#matcher

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


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

Solution

  • 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.