java - 如何用正则表达式替换某个索引处的字符

标签 java regex

嗨,我有这样的字符串

My home is a nice home in Paris but i will go to the home of some one else.

我想用正则表达式将字符串中从索引5到索引25开始的字符i替换为字符Z。

所以结果应该是

"My home Zs a nZce home Zn Paris but i will go to the home of some one else."

你能帮我吗?

我将在java应用程序中使用它 我必须创建一个网络服务来接收正则表达式、字符串、开始索引、结束索引,并且它必须返回修改后的字符串。

非常感谢。

最佳答案

您可以使用此正则表达式

(?<=^.{5,25})i

如果从行开头开始至少有 5 个且最多 25 个字符,则这将匹配“i”。

(?<=^.{5,25})lookbehind assertion ,检查此条件。

^anchor与字符串的开头匹配

String s = "My home is a nice home in Paris but i will go to the home of some one else.";
String res = s.replaceAll("(?<=^.{5,25})i", "Z");

输出:

My home Zs a nZce home Zn Paris but i will go to the home of some one else.

关于java - 如何用正则表达式替换某个索引处的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17213962/

相关文章:

java - EJB、 Spring 和 hibernate

ios - RegEx:如何在 NSPredicate 中使用正则表达式?

java - JSOUP 带有加载文本和圆圈的网页抓取页面

java - 使用 Android 时 Java 中的随机数

java - 无法在 Windows 上运行我的 Maven 项目

正则表达式结束字符可以是 2 个之一

python - 如何有效地删除非 ASCII 字符和数字,但保留重音 ASCII 字符

java - 如何否定正则表达式中的特定单词

javascript - Node.js 子进程中的数据丢失

java - 开发中如何避免在编译时浪费时间?