轻松的正则表达式捕获

时间:2016-07-20 13:09:03

标签: c# regex capture

使用C#Regex的新手,我试图从字符串中捕获两个逗号分隔的整数到两个变量。

示例:13,567

我尝试了

的变体
Regex regex = new Regex(@"(\d+),(\d+)");
var matches = regex.Matches("12,345");

foreach (var itemMatch in matches)
    Debug.Print(itemMatch.Value);

这只捕获1个变量,即整个字符串。我通过将捕获模式更改为"(\d+)"来解决这个问题,但是然后完全忽略了中间的逗号,如果整数之间有任何文本,我会得到一个匹配。 如何让它提取两个整数并确保它也看到逗号。

2 个答案:

答案 0 :(得分:3)

可以使用String.Split

执行此操作

为什么不使用拆分和解析?

var results = "123,456".Split(',').Select(int.Parse).ToArray();
var left = results[0];
var right = results[1];

或者,您可以使用循环并使用int.TryParse来处理失败,但是您正在寻找的内容应该涵盖它

如果您真的致力于正则表达式

您也可以使用Regex执行此操作,只需使用匹配组

即可
Regex r = new Regex(@"(\d+)\,(\d+)", RegexOptions.Compiled);
var r1 = r.Match("123,456");

//first is total match
Console.WriteLine(r1.Groups[0].Value);

//Then first and second groups

var left = int.Parse(r1.Groups[1].Value);
var right = int.Parse(r1.Groups[2].Value);

Console.WriteLine("Left "+ left);
Console.WriteLine("Right "+right);

制作dotnetfiddle您也可以测试解决方案

答案 1 :(得分:0)

使用Regex,您可以使用:

Regex regex = new Regex(@"\d+(?=,)|(?<=,)\d+");
var matches = regex.Matches("12,345");

foreach (Match itemMatch in matches)
    Console.WriteLine(itemMatch.Value);

打印:

12
345

实际上,这是在,

进行前瞻和后视
\d+(?=,)     <---- // Match numbers followed by a ,
|            <---- // OR
(?<=,)\d+    <---- // Match numbers preceeded by a ,
相关问题