开发者

Creating a Regex to replace characters [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 开发者_如何学Pythonyears ago.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜