Phong Ho
Phong Ho

Reputation: 31

Insert (single) spaces before and after a specific symbol

I need to insert (single) spaces before and after a specific symbol (e.g. "|"), like this:

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

This can easily be achieved using a couple 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 that is not what I want, my target is just use a single pattern.

I tried many ways but it still doesn't work as expected. Could anybody help me with this please.

Thank you so much in advance!

Upvotes: 3

Views: 136

Answers (3)

cat916
cat916

Reputation: 1361

Thanks @Santhosh Nayak.

I just write more C# code to get the output as OP want.

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(string input, string pattern, MatchEvaluator evaluator) in MSDN.

Upvotes: 4

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

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 " | ";
            });

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

We stil have |(space)(space)| between aaa and BBB but that is due to replacement of | with |.

Upvotes: 0

Santhosh Nayak
Santhosh Nayak

Reputation: 2288

Try This.

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

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

Upvotes: 0

Related Questions