Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 简单的正则表达式匹配问题,what';这是我的错吗?_C#_Regex - Fatal编程技术网

C# 简单的正则表达式匹配问题,what';这是我的错吗?

C# 简单的正则表达式匹配问题,what';这是我的错吗?,c#,regex,C#,Regex,我有一个字符串: 检查了1/45个文件 我想解析其中的数字(1和45),但首先要检查字符串是否与此模式匹配。所以我写了一个正则表达式: String line = "1/45 files checked"; Match filesProgressMatch = Regex.Match(line, @"[0-9]+/[0-9]+ files checked"); if (filesProgressMatch.Success) { String matched = filesProgress

我有一个字符串:

检查了1/45个文件

我想解析其中的数字(1和45),但首先要检查字符串是否与此模式匹配。所以我写了一个正则表达式:

String line = "1/45 files checked";
Match filesProgressMatch = Regex.Match(line, @"[0-9]+/[0-9]+ files checked");
if (filesProgressMatch.Success)
{
    String matched = filesProgressMatch.Groups[1].Value.Replace(" files checked", "");
    string[] numbers = matched.Split('/');
    filesChecked = Convert.ToInt32(numbers[0]);
    totalFiles   = Convert.ToInt32(numbers[1]);
}
我希望
matched
包含“1/45”,但实际上它是空的。我犯了什么错? 我的第一个想法是“/”是正则表达式中的一个特殊字符,但事实似乎并非如此

另外,有没有更好的方法从C#?

中的此类字符串中解析这些值,请尝试以下正则表达式:

你需要避开正斜杠

([0-9]+\/[0-9]+) files checked

使用捕获组:

Regex.Match(line, @"([0-9]+/[0-9]+) files checked");
#            here __^       and __^
您还可以使用两个组:

Regex.Match(line, @"([0-9]+)/([0-9]+) files checked");

您的正则表达式匹配,但您选择的是组[1],其中组数为1。所以使用

String matched = filesProgressMatch.Groups[0].Value.Replace(" files checked", "");

将替换操作应用于
fileprogressmath.Groups的第一个元素应该没问题

String matched = filesProgressMatch.Groups[0].Value.Replace(" files checked", "");

这会给你你的结果

string txtText = @"1\45 files matched";
int[] s = System.Text.RegularExpressions.Regex.Split(txtText, "[^\\d+]").Where(x => !string.IsNullOrEmpty(x)).Select(x => Convert.ToInt32(x)).ToArray();

我会在这里使用两个捕获组:)感谢演示链接!仅供参考,不仅不需要转义斜杠,而且会破坏匹配(至少在C#中)。哦,这就是捕获组的含义!因此我可以避免
拆分
删除