Parsing text with open close tags
-
27-09-2019 - |
Question
I need to parse Windows text file and extract all data related to operations. Operations are separated with $OPERATION and $OPERATION_END. What I need to do is extract all text blocks for all operations. How can I do it effectively using regex or simple String methods. I would appreciate you provide small snippet.
$OPERS_LIST
//some general data
$OPERATION
//some text block
$OPERATION_END
$OPERS_LIST_END
Solution
to get all operations from the list:
var input = @"$OPERS_LIST
//some general data
$OPERATION
erfgergwerg
ewrg//some text block
$OPERATION_END
$OPERATION
//some text block
$OPERATION_END
$OPERATION
//some text block
$OPERATION_END
$OPERS_LIST_END";
foreach (Match match in Regex.Matches(input, @"(?s)\$OPERATION(?<op>.+?)\$OPERATION_END"))
{
var operation = match.Groups["op"].Value;
// do something with operation...
}
OTHER TIPS
try {
if (Regex.IsMatch(subjectString, @"\$OPERATION(.*?)\$OPERATION_END", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)) {
// Successful match
} else {
// Match attempt failed
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Try an extension method like this. Just pass in the TextReader
that corresponds to the file you are reading from.
public static IEnumerable<string> ReadOperationsFrom(this TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
string line;
bool inOperation = false;
var buffer = new StringBuilder();
while ((line = reader.ReadLine()) != null) {
if (inOperation) {
if (line == "$OPERATION")
throw new InvalidDataException("Illegally nested operation block.");
if (line == "$OPERATION_END") {
yield return buffer.ToString();
buffer.Length = 0;
inOperation = false;
} else {
buffer.AppendLine(line);
}
} else if (line == "$OPERATION") {
inOperation = true;
}
}
if (inOperation)
throw new InvalidDataException("Unterminated operation block.");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow