我在 C# 中使用正则表达式。我想将匹配项移至新行并缩进。通过缩进,我的意思是应保留并添加预先存在的选项卡,这些选项卡存在于包含匹配的行的开头。
通过正则表达式匹配和替换来实现此目的的最佳方法是什么?
例如,匹配逗号后面的单词:
W 1, 2, 3
W 4, 5, 6
W 7, 8, 9
应该导致:
W 1,
2,
3
W 4,
5,
6
W 7,
8,
9
我可以匹配(?<=,)
,然后简单地替换为 \n
甚至\n\t
。但是,使用此方法时,每次匹配的缩进都会重置为一个选项卡,并且不会遵循预先存在的缩进。
我还尝试过使用命名组,例如通过 (?<tabs>^\t+|\n\t+)
查看现有缩进,并通过 (?<words>(?<=,))
缩进匹配。但是,我不知道如何将其组合成一个匹配和一个替换正则表达式模式。
最佳答案
这就是我的想法。它不使用任何正则表达式,因为此问题不需要使用它们。您可以自己决定这是否适合您:)
var input =
@"W 1, 2, 3
W 4, 5, 6
W 7, 8, 9";
var output = string.Empty;
var inputLines = input.Split('\n');
foreach(var inputLine in inputLines) {
// get leading whitespace for line... you can use Regex here to match
// more WS characters if you'd like
var leadingWsAmt = inputLine.Length - inputLine.TrimStart(' ').Length;
var leadingWs = new string(' ', leadingWsAmt);
// trim all strings separated by comma so whitespace is correct in final result
var inputsOnLine = inputLine
.Split(',')
.Select(x => x.Trim());
output += string.Join(",\n"+leadingWs+"\t", inputsOnLine);
// don't put comma after last item
output += "\n"+leadingWs+"\t";
}
output = output.Trim();
Console.WriteLine(output);
// W 1,
// 2,
// 3
// W 4,
// 5,
// 6
// W 7,
// 8,
// 9
关于c# - 正则表达式缩进 - 将制表符保留在行首,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858023/