C # replace string in text file

I am trying to replace a string in a text file.

I am using the following code:

string text = File.ReadAllText(@"c:\File1.txt");
text = text.Replace("play","123");
File.WriteAllText(@"c:\File1.txt", text);

It not only changes the word “play” to “123”, but also changes the word “display” to “dis123”

How to solve this problem?

+4
source share
5 answers

You can take advantage of Regular Expressions here.

\b Match the word boundary, this will solve your problem.

text = Regex.Replace(text, @"\bplay\b","123");

Read more about Regular Expressions

+11
source

You can use the following code snippets

var str = File.ReadAllText(@"c:\File1.txt");
                   var arr = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();

    for (int i = 0; i < arr.Count; i++)
    {
        if (arr[i].StartsWith("play"))
        {
            arr[i] = arr[i].Replace("play", "123");
        }
    }

    var res = string.Join(" ", arr);
File.WriteAllText(@"c:\File1.txt", result);

Also, it is case sensitive, make sure that this is what you want.

+2
source

, , :

:

static class Exts
{
    public static string GetLettersAndDigits(this string source)
    {
        return source.Where(char.IsLetterOrDigit)
            .Aggregate(new StringBuilder(), (acc, x) => acc.Append(x))
            .ToString();
    }

    public static string ReplaceWord(this string source, string word, string newWord)
    {
        return String.Join(" ", source
            .Split(new string[] { " " }, StringSplitOptions.None)
            .Select(x =>
            {
                var w = x.GetLettersAndDigits();
                return w == word ? x.Replace(w, newWord) : x;
            }));
    }
}

:

var input = File.ReadAllText(@"C:\test.txt");
var output = input.ReplaceWord("play", "123");

Console.WriteLine(input);
Console.WriteLine(output);

: , -play! play - , ?

This is a test: display 123, 123 display -123! 123 - maybe it works?

+2
source

Try changing it to

text.Replace(" play ","123");

but in this way it will not replace something like play. play, play;

0
source

Another way that you can use in this situation is to add more recognizable tokens to the text you want to edit. For example:

bla bla {PLAY} bla bla PLAY bla bla

will become

bla bla 123 bla bla PLAY bla bla
0
source

All Articles