我需要从字符串中获取一些信息,并且我想使用组名称来获取信息,但我无法得到正确的结果。
我的代码
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"发布于 2019-09-04 15:35:29
您可以使用
\AFilePath:\s*(?<FilePath>.*?),\s*ContentType:\s*(?<ContentType>.*?),\s*PrinterName:\s*(?<PrinterName>.*?),\s*DownloadFileName:\s*(?<DownloadFileName>.+)\z请参阅regex demo

基本上,正则表达式的所有部分都表示一些硬编码字符串(如FilePath:),然后是0+空格(与\s*匹配),然后是一个命名捕获组(如(?<FilePath>.*?)),该捕获组捕获除换行符以外的任何0+字符,次数尽可能少(而不是需要贪婪点模式的最后一个,即.+或.*)。
如果打印机名称部分可能丢失,则需要用(?:...)?括起,\s*PrinterName:\s*(?<PrinterName>.*?),即(?:,\s*PrinterName:\s*(?<PrinterName>.*?))?。
https://stackoverflow.com/questions/57783513
复制相似问题