List<int> ids = ExtractIds("United Kingdom (656) - Aberdeen (7707)");
上面的列表应该由下面的方法填充,它从括号内剥离值。如何将正则表达式match.Value转换为整数?
如果我使用match.Value作为字符串并将其分配给列表< string>它似乎工作正常。但是当我尝试将它转换为整数时,我得到错误:“输入字符串的格式不正确。”
我在做什么错?
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;
}
用其他语言的第0个匹配表示完全匹配字符串...对c#没有正面评价,但看起来好像是一个很好的地方 – Lucas 2013-03-13 15:36:47
你在匹配任何括号 - 你可能想用'\ d +'而不是'。 *?'。 – cfeduke 2013-03-13 15:36:53
您没有使用调试器。找出什么match.Value *是*,你会知道出了什么问题。 – nvoigt 2013-03-13 15:36:54