C# 如何找到具有特定模式的匹配字符串
我需要从一个大字符串缓冲区中找出所有与特定模式匹配的字符串 例如,我有一个字符串,如C# 如何找到具有特定模式的匹配字符串,c#,string,C#,String,我需要从一个大字符串缓冲区中找出所有与特定模式匹配的字符串 例如,我有一个字符串,如 "2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32" 我希望有这样的输出: 2014:11:12 13:30:05 ABCD 12:30 2014:11:12 13:31:05 ABBB 12
"2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32"
我希望有这样的输出:
2014:11:12 13:30:05 ABCD 12:30
2014:11:12 13:31:05 ABBB 12:31
2014:11:12 13:32:05 ABCC 12:32
我尝试过类似的代码,如:
string data = "2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32";
MatchCollection matches = Regex.Matches("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} Tested for [?]{4} at [0-9]{2}:[0-9]{2}");
/* But matches.count is always 0 here, looks like the pattern [?]{4} not work */
foreach (Match match in matches)
{
string temp = match.Value;
Match dateTime = Regex.Match(temp, "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");
Match Org = Regex.Match(temp, "Tested for [?]{4}").Value, "[?]{4}");
Match processingTime = Regex.Match(temp, "at [0-9]{2}:[0-9]{2}").Value, "[0-9]{2}:[0-9]{2}");
/* then parse the field datetime, Org and processingTime and write to console */
}
你可以用正则表达式来做。我不是这方面的专家,而且我确信有一个更好的正则表达式用于此工作,但这应该可以做到(省略错误捕获)
string input=“2014:11:12 13:30:05在12:30对ABCD进行测试2014:11:12 13:31:05在12:31对ABBB进行测试2014:11:12 13:32:05在12:32对ABCC进行测试”;
字符串regex=@“(\d{4}:\d{2}:\d{2}\d{2}:\d{2}:\d{2})在(\d{2}:\d{2})处测试(.*)”;
正则表达式r=新正则表达式(正则表达式);
var matchCollection=r.Matches(输入);
var outputStrings=matchCollection.Cast();
ForEach(str=>Console.WriteLine());
您能告诉我们您尝试过什么,并告诉我们哪些不起作用吗?也许我们可以帮你找出什么不起作用。
string input = "2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32";
string regex = @"(\d{4}:\d{2}:\d{2} \d{2}:\d{2}:\d{2}) Tested for (.*?) at (\d{2}:\d{2})";
Regex r = new Regex(regex);
var matchCollection = r.Matches(input);
var outputStrings = matchCollection.Cast<Match>().Select(m => string.Format("{0} {1} {2}", m.Groups[1], m.Groups[2], m.Groups[3])).ToList();
outputStrings.ForEach(str => Console.WriteLine());