c#替换文本文件中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19615624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:25:52  来源:igfitidea点击:

c# replace string in a text file

c#replace

提问by Quan

I am trying to replace string in a text file.

我正在尝试替换文本文件中的字符串。

I use 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 change the word "display" to "dis123"

它不仅将“播放”一词更改为“123”,还将“显示”一词更改为“dis123”

How to fix this problem?

如何解决这个问题?

回答by Anarion

Try changing it to

尝试将其更改为

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

but this way it won't replace something like play. play, play;

但这样它不会取代像 play. play, play;

回答by Sriram Sakthivel

You could take the advantage of "Regular expressions" here.

您可以在这里利用“正则表达式”。

\bMatches the word boundary, This will solve your problem.

\b匹配单词边界,这将解决您的问题。

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

Read more about Regular expressions

阅读有关正则表达式的更多信息

回答by serene

You can use following snippets of code

您可以使用以下代码片段

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, this is case sensitive make sure this is what you want.

此外,这是区分大小写的,请确保这是您想要的。

回答by ebb

An alternative approach, and not regex based could be the following:

一种替代方法,而不是基于正则表达式的方法如下:

Define a few extension methods:

定义几个扩展方法:

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

Usage:

用法:

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

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

Prints:

印刷:

This is a test: display play, play display -play !play - maybe it's working?

This is a test: display 123, 123 display -123 !123 - maybe it's working?

这是一个测试: display play, play display -play !play - 也许它起作用了?

这是一个测试: display 123, 123 display -123 !123 - 也许它正在工作?

回答by user230910

Another technique you can use in this situation is to add more recognizable tokens into the text you wish to edit.. for example:

在这种情况下,您可以使用的另一种技术是将更多可识别的标记添加到您要编辑的文本中……例如:

bla bla {PLAY} bla bla PLAY bla bla

would become

会成为

bla bla 123 bla bla PLAY bla bla