2

I need to get some information form a string, and I want to use group name to get information, but I can't do a correct result.

My Code

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;
}

I expect I can get FileNme, CreateTime, PrinterName, DownloadFileName information by the Regex, like this:

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

But actually, result with this regex is like this

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

1 Answer 1

1

You may use

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

See the regex demo

enter image description here

Basically, all parts of the regex represent some hardcoded string (like FilePath:), then 0+ whitespaces (matched with \s*) and then a named capturing group (like (?<FilePath>.*?)) that capture any 0+ chars other than a newline, as few times as possible (instead of the last one where the greedy dot pattern is required, .+ or .*).

If the printer name part can be missing you need to enclose ,\s*PrinterName:\s*(?<PrinterName>.*?) with (?:...)?, i.e. (?:,\s*PrinterName:\s*(?<PrinterName>.*?))?.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.