我需要解析的Windows文本文件,并提取相关业务的所有数据。操作 与$ OPERATION和$ OPERATION_END是分开的。我需要做的是提取所有文本块的所有操作。我怎样才能有效地做到这一点 使用正则表达式或简单的字符串方法。我将不胜感激您提供的小片断。

$OPERS_LIST
//some general data

$OPERATION
//some text block
$OPERATION_END


$OPERS_LIST_END
有帮助吗?

解决方案

从列表中得到所有操作:

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...
}

其他提示

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
}

尝试这样的扩展方法。只是通过在TextReader对应于您是从阅读该文件。

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.");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top