首页 > 解决方案 > 替换字符的第 n 个索引

问题描述

如何仅使用正则表达式替换字符的第 n 个索引。

string input = "%fdfdfdfdfdfdfdfdfdfdfdffd";
string result = Regex.Replace(input, "^%", "");

上面的代码用空字符串替换了第一个字符,但是,我想指定一个索引:比如第 n 个索引,以便将该字符替换为空字符串。

有人可以帮我吗?

标签: c#regex

解决方案


可以创建一个正则表达式模式来捕获替换字符之前和之后的所有字符,然后将整个字符串替换为由新字符分隔的两个捕获。例如:

Regex.Replace("abcdefgh", @"^(.{4}).(.*)$", @"$1E$2") // returns "abcdEfgh"

然后,您可以创建一个方法来替换特定索引处的字符:

string ReplaceCharacter(string text, int index, char value)
    => Regex.Replace(text, $@"^(.{{{index}}}).(.*)$", $@"${{1}}{value}${{2}}");

// Usage:
ReplaceCharacter("Foo-bar", 3, 'l') // returns "Foolbar"

推荐阅读