Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace repeating substring in string

I am working in java and I want to take the following string:

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

And I want to replace second "string" with "this is a much larger string", after some java magic the output would look like this:

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

I do have the offset of where the text starts. In this case, 40 and the text getting replaced "string".

I could do a:

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"

but is there a better way to do this other then using substring java functions?

EDIT -

The text "string" will be in the sample string at least once, but could be in that text numerous times, that the offset would dictate which one gets replaced (not always the second). So the string that needs to get replaced is always the one at the offset.

like image 538
Olin Blodgett Avatar asked Apr 24 '26 18:04

Olin Blodgett


2 Answers

One way you could do this..

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"
like image 174
hwnd Avatar answered Apr 27 '26 06:04

hwnd


Try the following:

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

$1 denotes the first group captured inside parentheses in the first argument.

like image 31
M A Avatar answered Apr 27 '26 08:04

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!