análisis de texto con etiquetas de cierre abiertas
-
27-09-2019 - |
Pregunta
Tengo que analizar el archivo de texto de Windows y extraer todos los datos relacionados con las operaciones. operaciones se separan con $ y $ FUNCIONAMIENTO OPERATION_END. Lo que tengo que hacer es extraer todos los bloques de texto para todas las operaciones. ¿Cómo puedo hacerlo con eficacia usando expresiones regulares o métodos de simple cadena. Le agradecería que usted proporciona pequeño fragmento.
$OPERS_LIST
//some general data
$OPERATION
//some text block
$OPERATION_END
$OPERS_LIST_END
Solución
para obtener todas las operaciones de la lista:
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...
}
Otros consejos
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
}
Trate de un método de extensión de esta manera. Sólo tiene que pasar en el TextReader
que se corresponde con el archivo que está leyendo.
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.");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow