如何使用正则表达式替换特定索引处的字符

时间:2013-06-20 12:44:00

标签: java regex

嗨,我有一个像这样的字符串

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

我想将字符串从索引5开始替换为字符串的索引25,并使用正则表达式替换字符。

所以结果应该是

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

你可以帮我吗?

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

非常感谢你。

4 个答案:

答案 0 :(得分:1)

使用StringBuffer

StringBuffer sb=new StringBuffer(input);
int index=-1;
while((index=sb.indexOf("i"))!=-1)
{
    if(index>=5&&index<=25)sb.setCharAt(index,'Z')
}

您可以使用此正则表达式i替换为Z

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

所以,你的代码将是

input.replaceAll(aboveRegex,"Z")

答案 1 :(得分:1)

您可以使用此正则表达式

(?<=^.{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");

输出:

  

我的家Zs nZce home Zn Paris但我将去其他人的家。

答案 2 :(得分:0)

你可以这样做(没有正则表达式): -

$str= "My home is a nice home in Paris but i will go to the home of some one else";
   for($i=5; $i<25; $i++) 
   if($str[$i]=='i')
         $str[$i] = 'Z';

         echo $str;

输出: -

我的家Zs nZce home Zn Paris但我将去其他人的家

答案 3 :(得分:0)

在Javascript中

var str = 'My home is a nice home in Paris but i will go to the home of some one else.';

var result = str.replace(str.substring(5, 25), function (match) {
    return match.replace(/i/g, 'Z');
});

console.log(result);