我需要插入一个特定符号之前和之后(单)空格(如“|”),像这样:插入(单)空格前的特定符号,之后
string input = "|ABC|xyz |123||999| aaa| |BBB";
string output = "| ABC | xyz | 123 | | 999 | aaa | | BBB";
这可以很容易地实现使用一些正则表达式模式:
string input = "|ABC|xyz |123||999| aaa| |BBB";
// add space before |
string pattern = "[a-zA-Z0-9\\s*]*\\|";
string replacement = "$0 ";
string output = Regex.Replace(input, pattern, replacement);
// add space after |
pattern = "\\|[a-zA-Z0-9\\s*]*";
replacement = " $0";
output = Regex.Replace(output, pattern, replacement);
// trim redundant spaces
pattern = "\\s+";
replacement = " ";
output = Regex.Replace(output, pattern, replacement).Trim();
Console.WriteLine("Original String: \"{0}\"", input);
Console.WriteLine("Replacement String: \"{0}\"", output);
但这不是我想要的,我的目标只是使用单一模式。
我尝试了很多方法,但仍然无法按预期工作。请有人帮我解决这个问题。
非常感谢你提前!
定义“不按预期工作”。你没有得到任何回报?错误的结果?一个错误? – Tim
没有错误,但错误的输出结果,例如有更多的空间比必要的(而不是1空间),这就是为什么我想要组合一些模式,但是有可能使用一个模式来实现这一点? –