List<int> ids = ExtractIds("United Kingdom (656) - Aberdeen (7707)");
上面的列表应该通过以下方法填充,该方法从括号内删除值。
如果我将match.Value用作字符串并将其分配给List&lt;字符串&gt;它似乎工作正常。但是当我尝试将其转换为整数时,我得到错误:“输入字符串的格式不正确。”
我做错了什么?
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 :(得分:9)
使用match.Groups[1].Value
代替match.Value
来获取括号内的字符串 - 即不包括括号本身。
使用\d*?
代替.?*
,以确保您只匹配数字,而不是括号中的任何内容!
然后您甚至不再需要?
,因为\d
与结束括号不匹配。
您可以在正则表达式中使用 lookarounds ,而不是切换到Groups[1]
,
(?<=\()\d(?=\))
确保Match
仅包含数字。
答案 1 :(得分:0)
如果您调试代码,则会得到匹配。值包括数字周围的括号,这显然会引发异常。
将您的模式重写为@“(\ d)+”这将对您的数字进行分组,但忽略括号。
public List<int> ExtractIds(string str)
{
MatchCollection matchCollection = Regex.Matches(str, @"(\d)+");
List<int> ExtractedIds = new List<int>();
foreach (Match match in matchCollection)
{
int theid = int.Parse(match.Value);
ExtractedIds.Add(theid);
}
return ExtractedIds;
}
希望这有帮助。