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

上面的列表应该由下面的方法填充,该方法从括号内删除值。

如果我使用 match.Value 作为字符串并将其分配给 List< 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;
}
4

2 回答 2

9

使用match.Groups[1].Value而不是match.Value只获取括号内的字符串 - 即不包括括号本身。

使用\d*?而不是.?*确保您只匹配数字,而不是括号中的任何内容!

然后你甚至不再需要了,?因为\d不匹配右括号。

Groups[1]您可以在正则表达式中使用lookarounds ,而不是切换到lookin ,例如

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

确保Match只包含数字本身。

于 2013-03-13T15:36:53.970 回答
0

如果你调试你的代码,你会得到 match.Value 包括数字周围的括号,这显然会抛出异常。

将您的模式重写为 @"(\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;
 }

希望这可以帮助。

于 2013-03-13T16:23:48.927 回答