Creating a Regex to replace characters [closed]
I want to build Regex in C#, the Regex maches char and swap it to another clone char. (e.g. swape 1 to 2,but 2 to 4 etc.)
How can I do it?
Thanks
Use a MatchEvaluator. Example:
string s = "asdf12345";
s = Regex.Replace(s, "[123]", m => {
switch (m.Value) {
case "1": return "2";
case "2": return "3";
case "3": return "1";
}
return m.Value;
});
Console.WriteLine(s);
Output:
asdf23145
You can also do the same by getting the string as a character array, replace the characters you want, and create a string from the array:
char[] c = s.ToCharArray();
for (int i = 0; i < c.Length; i++) {
switch (c[i]) {
case '1': c[i] = '2'; break;
case '2': c[i] = '3'; break;
case '3': c[i] = '1'; break;
}
}
s = new String(c);
精彩评论