如果可以的话,我会避免使用\r\n 和类似的硬编码字符。下面的示例对我有用。
static void Main() {
var str = @"List item 1
List item 2
Account
Number
Five
List item 3
List item 4
Account
Number
Six
List item 5";
var newStr = Regex.Replace(str, @"^\s*(Account)\s*^\s*(.*?)\s*$\s*^\s*(.*?)\s*$", "$1 $2 $3", RegexOptions.Multiline | RegexOptions.Singleline);
Console.WriteLine($"Original: \r\n{str}\r\n---------------\r\n");
Console.WriteLine($"New: \r\n{newStr}\r\n---------------\r\n");
}
下面是它的输出
Original:
List item 1
List item 2
Account
Number
Five
List item 3
List item 4
Account
Number
Six
List item 5
---------------
New:
List item 1
List item 2
Account Number Five
List item 3
List item 4
Account Number Six
List item 5
---------------
正则表达式解释:
^\s*(Account)\s* - Match from start of line followed by Account. If there are white spaces around account, then eat them up too.
^\s*(.*?)\s*$\s* - Match from start of line, followed by optional white-spaces, followed by capturing all text on that line, followed by optional white-spaces, and then end-of-line. The last \s* eats up the end-of-line character(s)
^\s*(.*?)\s*$ - Same as above explanation, except that we don't want to eat up the end-of-line character(s) at the end
替换:
"$1 $2 $3" - the 3 items we captured in the above regex with a space in between them.
正则表达式选项:
MultiLine - ^ and $ character will match beginning and end of any line and not just the start and end of the string