替换字符串中的重复子字符串

时间:2014-09-11 18:45:58

标签: java regex string replace substring

我在java工作,我想采用以下字符串:

String sample = "This is a sample string for replacement string with other string";

我想替换第二个"字符串"使用"这是一个更大的字符串",在一些java魔术之后输出看起来像这样:

System.out.println(sample);
"This is a sample string for replacement this is a much larger string with other string"

我确实有文本开始的偏移量。在这种情况下,40和文本被替换"字符串"。

我可以做:

int offset = 40;
String sample = "This is a sample string for replacement string with other string";
String replace = "string";
String replacement = "this is a much larger string";

String firstpart = sample.substring(0, offset);
String secondpart = sample.substring(offset + replace.length(), sample.length());
String finalString = firstpart + replacement + secondpart;
System.out.println(finalString);
"This is a sample string for replacement this is a much larger string with other string"

但除了使用子字符串java函数之外,还有更好的方法吗?

编辑 -

文字"字符串"将在样本字符串中至少一次,但可能在该文本中多次,偏移将指示哪一个被替换(不总是第二个)。因此需要替换的字符串始终是偏移量的字符串。

4 个答案:

答案 0 :(得分:2)

使用indexOf()的重载版本,它将起始indes作为第二个参数:

str.indexOf("string", str.indexOf("string") + 1);

获取2个字符串的索引...然后将其替换为此偏移量...希望这会有所帮助。

答案 1 :(得分:2)

尝试以下方法:

sample.replaceAll("(.*?)(string)(.*?)(string)(.+)", "$1$2$3this is a much larger string$5");

$1表示在第一个参数中括号内捕获的第一个组。

答案 2 :(得分:2)

你可以做到这一点..

String s = "This is a sample string for replacement string with other string";
String r = s.replaceAll("^(.*?string.*?)string", "$1this is a much larger string");
//=> "This is a sample string for replacement this is a much larger string with other string"

答案 3 :(得分:1)

您可以使用

str.indexOf("string", str.indexOf("string") + 1);

而不是你的偏移,仍然使用你的子串替换它。