我有一个生成的输入字符串,如下例所示:
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;
}
可能值得重构以返回包含所有所需信息的复合类型,而不是使用 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/