c# - 替换字符的第 n 个索引
问题描述
如何仅使用正则表达式替换字符的第 n 个索引。
string input = "%fdfdfdfdfdfdfdfdfdfdfdffd";
string result = Regex.Replace(input, "^%", "");
上面的代码用空字符串替换了第一个字符,但是,我想指定一个索引:比如第 n 个索引,以便将该字符替换为空字符串。
有人可以帮我吗?
解决方案
可以创建一个正则表达式模式来捕获替换字符之前和之后的所有字符,然后将整个字符串替换为由新字符分隔的两个捕获。例如:
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"
推荐阅读
- c++ - 向量反序列化的 YAML BadConversion 异常
- java - ConnectionPool 放弃连接已被放弃
- nao-robot - Nao机器人各板低级日志
- javascript - Firefox扩展如何获取扩展存储值
- android - image_picker maxDuration 不限制画廊选择中的视频(Android 或 iOS) - Flutter
- python - 将某些文件行值存储在不同的列表中
- reactjs - 依赖 React 重用现有的 DOM 元素(例如 CSS 转换)是否安全?
- java - java.lang.indexoutofboundsexception index 0 size 0 setQuestionMethod() 中的问题
- sql - Postgres - 连接三个表并在查询中对数据使用聚合函数
- swift - 只显示图片的百分比,swiftUI