Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert regex match.Value to integer?

Tags:

c#

regex

List<int> ids = ExtractIds("United Kingdom (656) - Aberdeen (7707)");

The above list should be populated by the method below, which strips the values from within parenthesis.

If I use match.Value as a string and assign it to List< string > it seems to work ok. But when I try to convert it to an integer I get the error: "Input string was not in a correct format."

What am I doing wrong?

public List<int> ExtractIds(string str)
{
    MatchCollection matchCollection = Regex.Matches(str, @"\((.*?)\)");
    List<int> ExtractedIds = new List<int>();
    foreach (Match match in matchCollection)
    {
        int theid = int.Parse(match.Value);
        ExtractedIds.Add(theid);
    }

    return ExtractedIds;
}
like image 502
Martin Hansen Lennox Avatar asked Sep 17 '25 10:09

Martin Hansen Lennox


1 Answers

Use match.Groups[1].Value instead of match.Value to just get the string found inside the brackets - i.e. not including the brackets themselves.

Use \d*? instead of .?* to ensure you're only matching digits, not anything in brackets!

Then you don't even need the ? any more because \d doesn't match a closing bracket.

Instead of switching to look in Groups[1], you can use lookarounds in a regular expression such as

(?<=\()\d(?=\))

to make sure Match only contains the digits themselves.

like image 92
Rawling Avatar answered Sep 19 '25 01:09

Rawling