DefColin DefColin - 25 days ago 6
C# Question

How to replace specific strings with spaces on sides into text file if it is merged with text

I'm trying to replace specific strings in text document, if it is written there merged with other text

for example document content is:

a1some textb2
some c2c1text a1
c1 some text c2d2
some textd2


I want get this result:

a1 some text b2
some c2 c1 text a1
c1 some text c2 d2
some text d2


So seems like it is a wrong way:

string text = File.ReadAllText(path);
text = text.Replace("a1", " a1 ").Replace("b2", " b2 ")
.Replace("c1", " c1 ").Replace("d2", " d2 ");
File.WriteAllText(path, text);


Because in result I have something like this:

a1
some text b2
some c2 c1 text a1
c1 some text c2 d2
some text d2

Answer

You can try this Regex:

\s?(a1|b2|c1|d2)\s?

Here is how to do it in C#:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var text = @"a1some textb2";
        var pattern = @"\s?(a1|b2|c1|d2)\s?";
        var replaced = Regex.Replace(text, pattern, " $1 ");

        Console.WriteLine(replaced);

    }
}

Demo: https://dotnetfiddle.net/xf0BVO