c# - 如何匹配正确的组名(.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"
解决方案
您可以使用
\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>.*?))?
。
推荐阅读
- javascript - 我在哪个 iframe 中?
- http - 我可以在 nginx 上游同时使用 HTTP 和 HTTPS 吗?
- python - 检查 IF 中的空 str
- python - 计算给定时间跨度内的触发器数量
- c++ - 获取非托管 C/C++ 中已签名 EXE 的 X509 代码签名证书序列号
- wordpress - SASS WordPress 的 Owl Carousel 安装
- reactjs - 在 Modal 中更改 Element 的类
- excel - 如何从 2 列报告重叠的单元格值
- python - 如何通过它的 ID 从 PanedWindow 获取小部件?
- syntax - 尝试导入 `reqwest::async` 错误,指出 `async` 是保留关键字