Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 替换字符串中的重复子字符串_Java_Regex_String_Replace_Substring - Fatal编程技术网

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

Java 替换字符串中的重复子字符串,java,regex,string,replace,substring,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

我在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”将至少出现在示例字符串中一次,但可能多次出现在该文本中,偏移量将指示替换哪一个(不总是第二个)。因此,需要替换的字符串始终是偏移量处的字符串。

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

str.indexOf("string", str.indexOf("string") + 1);
要获取2字符串的索引。。。然后用这个偏移量替换它。。。希望这会有所帮助。

您可以使用

str.indexOf("string", str.indexOf("string") + 1);
而不是偏移量,并且仍然使用子字符串替换它。

请尝试以下操作:

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

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

可以这样做

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"

您是否只是在尝试有效地使“这是一个用于替换的示例字符串,这是一个更大的字符串,其他字符串”或您是否在寻找一种方法来替换未知字符串中“字符串”的特定实例?要解决“用替换字符串替换源字符串偏移量N处开始的M个字符”问题,我会说不——据我所知,没有比子字符串更好的方法了。除非Apache Commons或其他第三方库中有某些内容。