c#中使用正则表达式操作字符串

本文关键字:操作 字符串 正则表达式 | 更新日期: 2023-09-27 18:02:24

我目前有一个regex方法,从现有的文本文件中删除特定的一系列字符,尽管我怎么能用字符串代替呢?

。从s string

中删除任何出现的"xyz"

目前为止的代码:

var result = Regex.Replace(File.ReadAllText(@"Command.bat"), @"test", string.Empty);
System.IO.File.WriteAllText(@"Command.bat", result);

c#中使用正则表达式操作字符串

如果您想使用字符串,您可以使用字符串的Replace函数。

var line = "bansskgngxyz".Replace("xyz","");

嗯…它已经用字符串做过了。ReadAllText返回一个字符串,WriteAllText返回一个字符串…所以你所要做的就是把File.ReadAllText变成一个字符串,你就完成了。

换句话说:

var result = Regex.Replace(@"test string", @"test", string.Empty);
System.IO.File.WriteAllText(@"Command.bat", result);
编辑:

上面的代码可以重写为:

string s = File.ReadAllText(@"Command.bat");
var result = Regex.Replace(s, @"test", string.Empty);
System.IO.File.WriteAllText(@"Command.bat", result);

如你所见,正则表达式。Replace已经接受了一个字符串,这会让它更清楚吗?

string s = "xyz";
var newS = Regex.Replace(s, "test", "");