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

标签 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/2011. The process was completed 
45 milliseconds and data was received.

一旦从不同的应用程序接收到这样的字符串,使用正则表达式解析并提取值的最简单方法是什么 Document.docx, John, 1/1/201145 来自它。

我正在寻找执行此操作的最简单方法,因为我们将不得不解析许多不同的输入字符串。

最佳答案

你可以使用这样的东西:

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

可能值得重构以返回包含所有所需信息的复合类型,而不是使用 out 参数。但这种方法应该仍然有效。

要使用此代码,您需要执行以下操作:

var input = "...";

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

关于c# - 使用正则表达式从字符串中提取多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4635227/

相关文章:

c# - 查找所有已安装字体的后记名称

C# 抽象类,用于数组初始化

regex - XSL : how can I generate a regex pattern on demand?

c# - Web API POST MultipartFormDataContent : Can response return multipartform content?

c# - 使用模型值包括报价 ASP MVC4

c# - 可空类型之间的转换

c# - 在 Windows 窗体 DataGridView 单元格中托管 TreeView

c# - 您如何看待我的 IDisposable 模式实现?

regex - 除了使用正则表达式之外,在 Swift 中解析 HTML

regex - 在 Scala 中使用正则表达式进行分组和模式匹配