我有一个C#程序,它通过SAS日志,我希望它提取错误的行。
例如,如果我的日志文件包含以下行:
WARNING: Apparent invocation of macro EDIT_TEXT not resolved.
ERROR 180-322: Statement is not valid or it is used out of proper order.
ERROR: SAS ended due to errors.
You specified: OPTIONS ERRORABEND;.
ERROR: Errors printed on page 4.
NOTE: SAS Institute Inc., SAS Campus Drive, Cary, NC USA 27513-2414
NOTE: The SAS System used:
real time 1.37 seconds
cpu time 0.38 seconds
我想回来
ERROR: SAS ended due to errors. You specified: OPTIONS ERRORABEND;.
ERROR: Errors printed on page 4.
但它只返回
ERROR: SAS ended due to errors.
这是我正在使用的代码:
Match match;
Regex regex;
StreamReader sr;
string log;
sr = new StreamReader(path + ".log");
log = sr.ReadToEnd();
sr.Close();
regex = new Regex("ERROR: [^\\r]+\\r");
match = regex.Match(log);
我不确定在正则表达式上要更改什么来修复它。感谢
答案 0 :(得分:0)
你可以尝试这个正则表达式。如果您有超过NOTE:或ERROR:,则应以类似的方式添加它们。
ERROR:(.*\n?.*)(NOTE:|ERROR:)?
此正则表达式包含存储在第1组中的错误信息。
其次,非正则表达式方法:
string yourLogText = "you log text";
string[] lines = yourLogText.Split(new string[1] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string builtErrorText = "";
Boolean isBuildingError = false;
List<String> resultingErrors = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].StartsWith("ERROR:"))
{
isBuildingError = true;
if (!String.IsNullOrEmpty(builtErrorText))
resultingErrors.Add(builtErrorText);
builtErrorText = lines[i];
}
else if (lines[i].StartsWith("NOTE:") || lines[i].StartsWith("WARNING:"))
{
isBuildingError = false;
if (!String.IsNullOrEmpty(builtErrorText))
resultingErrors.Add(builtErrorText);
}
else if (isBuildingError)
{
// If you want them to appear on different lines.
builtErrorText += Environment.NewLine + lines[i];
}
}
}
// In case it ends with an error
if (String.IsNullOrEmpty(builtErrorText))
resultingErrors.Add(builtErrorText);