Insert (single) spaces before and after a specific character

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!

+4
source share
3 answers

Thanks @Santhosh Nayak.

I am just writing more C # code to get the result like OP.

string input = "|ABC|xyz |123||999|   aaa|   |BBB";
string pattern = @"[\s]*[|][\s]*";
string replacement = " | ";
string output = Regex.Replace(input, pattern, (match) => {
     if(match.Index != 0)
        return replacement;
     else
        return value;
});

I refer to Regex.Replace (line input, line pattern, MatchEvaluator evaluator) on MSDN.

+4

.

string input = "|ABC|xyz |123||999|   aaa|   |BBB";

string pattern = @"[\s]*[|][\s]*";
string replacement = " | ";
string output = Regex.Replace(input, pattern, replacement);
+1

Try this solution based on this answer :

var str = "|ABC|xyz |123||999|   aaa|   |BBB";
var fixed = Regex.Replace(str, patt, m =>
            {
                if(string.IsNullOrWhiteSpace(m.Value))//multple spaces
                    return "";
                return " | ";
            });

It returns | ABC | xyz | 123 | | 999 | aaa | | BBB

We have |(space)(space)|between aaaand BBB, but this is due to replacing |with |.

0
source

Source: https://habr.com/ru/post/1656757/


All Articles