c#替换文本文件中的字符串 [英] c# replace string in a text file

查看:124
本文介绍了c#替换文本文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to replace string in a text file.

我使用以下代码:

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

它不仅把play"这个词改成了123"而且把display"这个词改成了dis123"

It not only changes the word "play" to "123" but also change the word "display" to "dis123"

如何解决这个问题?

推荐答案

您可以在这里利用正则表达式".

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

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

\b Matches the word boundary, This will solve your problem.

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

阅读有关正则表达式

这篇关于c#替换文本文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆