2013-03-13 63 views
3
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; 
} 
+1

用其他语言的第0个匹配表示完全匹配字符串...对c#没有正面评价,但看起来好像是一个很好的地方 – Lucas 2013-03-13 15:36:47

+0

你在匹配任何括号 - 你可能想用'\ d +'而不是'。 *?'。 – cfeduke 2013-03-13 15:36:53

+2

您没有使用调试器。找出什么match.Value *是*,你会知道出了什么问题。 – nvoigt 2013-03-13 15:36:54

回答

9

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

使用\d*?而不是.?*,以确保您只匹配数字,括号内没有什么!

然后,您甚至不需要?,因为\d与右括号不匹配。

相反的切换Groups[1]看,你可以使用lookarounds正则表达式,如

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

确保Match只包含数字本身。

+0

或者,您可以使用命名的捕获组而不是整数索引组 - 记住'match.Groups [2]'或更多也可能存在,以及根本没有匹配。你的代码应该考虑到这一点。 – cfeduke 2013-03-13 15:39:06

+0

是的 - 用这样一个简单的正则表达式我不会太担心,但更复杂的东西,我会考虑命名捕获。 – Rawling 2013-03-13 15:40:03

+0

非常感谢大家提供的信息丰富的答案和例子 - 现在都很好,并有一些有价值的改进。 – 2013-03-13 17:32:34

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; 
} 

希望这会有所帮助。

相关问题