嗨,我有这样的字符串
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/