I am looking for an elegant way to replace a string after a particular word in a text with Java. Example: "Today we have an IKAR ME123 from Greece." I want to replace the word after "IKAR" with my custom string, lets say XXXX , then the text should look: "Today we have an IKAR XXXX from Greece." Is there a nice way of doing it ,without have to write some ugly regular expression or 200 lines of code ?I've looked on Stackoverflow , and even though i found "similar" questions , non adressed that particular situation !
Thanks in advance
CodePudding user response:
"Today we have an IKAR ME123 from Greece."
.replaceFirst("IKAR \\w ","IKAR XXXX");
CodePudding user response:
public class ReplaceText {
public static void main(String[] args) {
String input = "Today we have an IKAR ME123 from Greece";
String replacement = "XXXX";
System.out.println( replaceBetween( input, "IKAR ", " from", replacement ) );
}
private static String replaceBetween( String input, String start, String end, String replacement ) {
return input.substring( 0, input.lastIndexOf( start ) start.length() ) replacement input.substring( input.lastIndexOf( end ) );
}
}