Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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# 使用正则表达式分析给定字符串中的值_C#_Regex - Fatal编程技术网

C# 使用正则表达式分析给定字符串中的值

C# 使用正则表达式分析给定字符串中的值,c#,regex,C#,Regex,我有这个字符串: String str = "Displaying bills 1 - 20 of 10000 in total"; 我想解析总值,10000,在本例中。 这就是我所尝试的: Regex regex = new Regex(@"\\d+(?=\\s*in total)"); Match match = regex.Match("Displaying bills 1 - 20 of 10000 in total"); if (match.Success) { Consol

我有这个
字符串

String str = "Displaying bills 1 - 20 of 10000 in total";
我想解析总值,
10000
,在本例中。 这就是我所尝试的:

Regex regex = new Regex(@"\\d+(?=\\s*in total)");
Match match = regex.Match("Displaying bills 1 - 20 of 10000 in total");
if (match.Success)
{
    Console.WriteLine(match.Value);
} 

现在这项工作已经成功。

正如@juharr在评论中提到的,您只需要删除双反斜杠。字符串开头的
@
将其标记为逐字字符串,不需要转义特殊字符。

不要在逐字字符串中分隔反斜杠。因此,请使用
@“\d+(?=\s*总计)”
“\\d+(?=\\s*总计)”
(无
@
)。是的,
@“
表示1个文字反斜杠,在
d
之前有2个,匹配文本中的
\
d
。当您删除
@
并将字符串文字设置为常规字符串时,
“\\”
将被解析为正则表达式引擎将
\d
解析为数字速记字符类所需的1个文字反斜杠。唯一的问题是带分隔符的反斜杠,因为OP只想匹配“总计”之前的数字. 您的将匹配整个字符串。您是正确的。出于某种原因,我认为他是从match.groups[1]中获取值的,这需要对数字进行分组。我会编辑。为什么要转义不包含任何需要转义的字符串文字?
        string text = "Displaying bills 1 - 20 of 10000 in total";
        Regex r = new Regex(Regex.Escape("of") +"(.*?)"+Regex.Escape("in"));
        MatchCollection matches = r.Matches(text);
        MessageBox.Show(matches[0].Groups[1].Value);