正则表达式 (.NET) 用于可变宽度的后视 - 查找逻辑行

Regex (.NET) for look-behind with variable width - finding logical lines

我有一个文本文件,其中逻辑行由物理行组成,物理行通过“!”继续。在该行的末尾。以下文本(没有尾随换行符)将是 7 条物理行,但只有 4 条逻辑行:

Single line logical line, followed by an empty line

Start of Logical line !
  indented End Of Logical Line
Start of Logical Line !
unindented logical line content !
End Of Logical Line (without trailing line-feed)

我得到了返回的 5 个匹配项(最后一个匹配项是不需要的):

(?<logical_line>(?:[^\n]| +! *\n)*)(?<! !)(?:\n|\Z)

上面的示例文本允许使用“!”行继续标记,但我需要处理 white-space 出现在“!”之前和之后的实例- 例如:“+! *”,但是 IIUC,在回顾中使用它是无效的。也就是说,我需要能够将其识别为单个逻辑行:

Some line with lots of spaces before and after the shriek     !     
end of line

那里有一个非常复杂的正则表达式。等效的过程代码可能看起来不漂亮,但它足够高效且易于阅读和理解。

var input = File.ReadAllLines(@"TextFile1.txt");
var str = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
    var line = input[i];
    while (line.EndsWith("!"))
    {
        i++;
        line += input[i];
    }
    str.AppendLine(line);
}

你不需要使用lookbehind,你只需要描述你想要匹配的内容看起来如何:

(?m)(?<logical_line>^[^\n!]*(?: !\s*[^\n!]*)*$\n?)

demo