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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With