简体   繁体   English

如何将regex match.Value转换为整数?

[英]How to convert regex match.Value to integer?

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. 如果我使用match.Value作为字符串并将其分配给List <string>它似乎工作正常。 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 - ie not including the brackets themselves. 使用match.Groups[1].Value而不是match.Value来获取括号内找到的字符串 - 即不包括括号本身。

Use \\d*? 使用\\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. 因为\\d与结束括号不匹配。

Instead of switching to look in Groups[1] , you can use lookarounds in a regular expression such as 您可以在正则表达式中使用lookarounds ,而不是切换到在Groups[1]查找

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

to make sure Match only contains the digits themselves. 确保Match仅包含数字本身。

If you debug your code, you are getting match.Value includes the brackets around the number, this will obviously throw exception. 如果你调试你的代码,你得到匹配。值包括数字周围的括号,这显然会抛出异常。

rewrite you pattern as @"(\\d)+" this will group your number but ignore the brackets. 将模式重写为@“(\\ 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;
 }

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM