I need to insert (single) spaces before and after a certain character (for example, "|"), for example:
string input = "|ABC|xyz |123||999| aaa| |BBB";
string output = "| ABC | xyz | 123 | | 999 | aaa | | BBB";
This can be easily achieved with a pair of regular expression patterns:
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);
But this is not what I want, my goal is just using one template.
I tried many ways, but it still does not work properly. Can someone help me with this please.
Thank you so much in advance!
source
share