首页 > 解决方案 > 如何匹配正确的组名(.NET C# Regex)

问题描述

我需要从字符串中获取一些信息,并且我想使用组名来获取信息,但我无法得到正确的结果。

我的代码

Regex _Regex = new Regex(@"\AFilePath: (?<FilePath>.+), ContentType: (?<ContentType>.+)[, PrinterName: ]? (?<PrinterName>.+),DownloadFileName: (?<DownloadFileName>.+)\z");
    string _String = @"FilePath: C:\Download\TEST.docx, ContentType: WORD, PrinterName: RICOH Aficio MP C4501 PCL 6, DownloadFileName: TEST.docx";
    Match _Match = _Regex.Match(_String);
    if (_Match.Success == true)
{
  string FileNme = _Match.Groups["FilePath"].Value;
  string ContentType = _Match.Groups["ContentType"].Value;
  string PrinterName = _Match.Groups["PrinterName"].Value;
  string DownloadFileName = _Match.Groups["DownloadFileName"].Value;
}

我希望我可以通过正则表达式获取 FileNme、CreateTime、PrinterName、DownloadFileName 信息,如下所示:

FileNme = "C:\Download\TEST.docx"
ContentType = "WORD"
PrinterName = "RICOH Aficio MP C4501 PCL 6"
DownloadFileName = "TEST.docx"

但实际上,这个正则表达式的结果是这样的

FileNme = "C:\Download\TEST.docx"
ContentType = "WORD, PrinterName:  RICOH Aficio MP C4501 PCL"
PrinterName = "6"
DownloadFileName = "TEST.docx"

标签: c#regex

解决方案


您可以使用

\AFilePath:\s*(?<FilePath>.*?),\s*ContentType:\s*(?<ContentType>.*?),\s*PrinterName:\s*(?<PrinterName>.*?),\s*DownloadFileName:\s*(?<DownloadFileName>.+)\z

查看正则表达式演示

在此处输入图像描述

基本上,正则表达式的所有部分都表示一些硬编码的字符串(如),然后是0+FilePath:空格(与 匹配\s*),然后是一个命名的捕获组(如(?<FilePath>.*?)最后一个需要贪心点图案的地方,.+.*)。

如果打印机名称部分可能丢失,您需要用 括,\s*PrinterName:\s*(?<PrinterName>.*?)起来(?:...)?,即(?:,\s*PrinterName:\s*(?<PrinterName>.*?))?


推荐阅读