我需要插入一個特定符號之前和之後(單)空格(如「|」),像這樣:插入(單)空格前的特定符號,之後
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空間),這就是爲什麼我想要組合一些模式,但是有可能使用一個模式來實現這一點? –