Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.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#_.net_Regex - Fatal编程技术网

C# 使用正则表达式从字符串中提取多个值

C# 使用正则表达式从字符串中提取多个值,c#,.net,regex,C#,.net,Regex,我有一个输入字符串,其生成如以下示例所示: string.Format("Document {0}, was saved by {1} on {2}. The process was completed {3} milliseconds and data was received.", "Document.docx", "John", "1/1/2011", 45); 它生成的字符串如下所示: Document Document.docx, was saved by John on 1/1

我有一个输入字符串,其生成如以下示例所示:

string.Format("Document {0}, was saved by {1} on {2}. The process was completed 
{3} milliseconds and data was received.", 
"Document.docx", "John", "1/1/2011", 45);
它生成的字符串如下所示:

Document Document.docx, was saved by John on 1/1/2011. The process was completed 
45 milliseconds and data was received.
一旦从不同的应用程序接收到这样的字符串,用正则表达式解析并从中提取值
Document.docx
John
1/1/2011
45
的最简单方法是什么


我正在寻找最简单的方法,因为我们必须解析许多不同的输入字符串

您可以使用以下内容:

private static readonly Regex pattern =
    new Regex("^Document (?<document>.*?), was saved by (?<user>.*?) on " +
        "(?<date>.*?)\\. The process was completed (?<duration>.*?) " +
        "milliseconds and data was received\\.$");

public static bool MatchPattern(
    string input,
    out string document,
    out string user,
    out string date,
    out string duration)
{
    document = user = date = duration = null;

    var m = pattern.Match(input);
    if (!m.Success)
        return false;

    document = m.Groups["document"].Value;
    user = m.Groups["user"].Value;
    date = m.Groups["date"].Value;
    duration = m.Groups["duration"].Value;

    return true;
}
var input = "...";

string document, user, date, duration;
if (MatchPattern(input, out document, out user, out date, out duration)) {
    // Match was successful.
}

太棒了,你救了我的一天:-)试图找到python等价物:/