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

标签 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 函数之外,还有更好的方法吗?

编辑 -

文本“string”将在示例字符串中至少出现一次,但可能会多次出现在该文本中,偏移量将决定替换哪一个(并不总是第二个)。因此需要替换的字符串始终是偏移量处的字符串。

最佳答案

你可以这样做的一种方式..

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"

关于java - 替换字符串中的重复子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794908/

相关文章:

javascript - Javascript 正则表达式中的分组是如何工作的?

regex - 从类似 JSON 的数据中删除 ": "

c++ - C++ 中用于并行化的字符串数组

java - 尝试将 Dart 程序转换为 Java

java - javafx中的可编辑 ListView

Java,如何检测对象的属性何时发生变化

java - 编写cookie Java : Getting the server to set/use a cookie

php垂直正则表达式搜索

java - jvm字符串池intern中有多少个字符串

c++ - 正确查找字符串中的数字?