Using regex to manipulate string in C#
I currently have a regex method that removes a specific series of characters from an existing text file, although how could I d开发者_运维知识库o this with a string instead?
e.g. remove any occurrences of "xyz" from s string
The code I have so far:
var result = Regex.Replace(File.ReadAllText(@"Command.bat"), @"test", string.Empty);
System.IO.File.WriteAllText(@"Command.bat", result);
If you want to use string you can use the Replace
function of the string.
var line = "bansskgngxyz".Replace("xyz","");
Uhh.. it already does it with a string. ReadAllText returns a string, and WriteAllText writes a string... so all you have to do is change the File.ReadAllText
to a string and you're done.
In other words:
var result = Regex.Replace(@"test string", @"test", string.Empty);
System.IO.File.WriteAllText(@"Command.bat", result);
EDIT:
Your code above can be rewritten as:
string s = File.ReadAllText(@"Command.bat");
var result = Regex.Replace(s, @"test", string.Empty);
System.IO.File.WriteAllText(@"Command.bat", result);
So as you can see, Regex.Replace already accepts a string, does this make it any more clear?
string s = "xyz";
var newS = Regex.Replace(s, "test", "");
精彩评论