Skip to main content
 首页 » 编程设计

c#之正则表达式 : extract numbers separated by commas from strings

2024年01月28日27zhoujg

我需要从这样的字符串中提取用逗号分隔的数字(数字和空格的数量是任意的):

Expression type:            Answer: 
(1, 2,3)                    1,2,3 
(1,3,4,5,77)                1,3,4,5,77 
( b(2,46,8,4,5, 52)    y)   2,46,8,4,5,52 
(a (3, 8,2, 1, 2, 9) x)     3,8,2,1,2,9 

请您参考如下方法:

试试这个模式:

\((?:\s*\d+\s*,?)+\) 

例如:

var results = Regex.Matches(input, @"\((?:\s*\d+\s*,?)+\)"); 
Console.WriteLine(results[0].Value); // (1,2,3) 

如果您想将其转换为整数列表,您可以使用 Linq 轻松完成此操作:

var results = Regex.Matches(input, @"\((?:\s*(\d+)\s*,?)+\)") 
                   .Cast<Match>() 
                   .SelectMany(m => m.Groups.Cast<Group>()).Skip(1) 
                   .SelectMany(g => g.Captures.Cast<Capture>()) 
                   .Select(c => Convert.ToInt32(c.Value)); 

或者在查询语法中:

var results =  
    from m in Regex.Matches(input, @"\((?:\s*(\d+)\s*,?)+\)").Cast<Match>() 
    from g in m.Groups.Cast<Group>().Skip(1) 
    from c in g.Captures.Cast<Capture>() 
    select Convert.ToInt32(c.Value);