如何在文本中的特定字符串之后替换字符串



我正在寻找一种优雅的方法来用Java替换文本中特定单词后面的字符串。示例:"今天我们有一辆来自希腊的IKAR ME123"我想把";IKAR";使用我的自定义字符串,比如XXXX,那么文本应该看起来:"今天我们有一辆来自希腊的IKARXXXX"有没有一种很好的方法可以做到这一点,而不必编写一些丑陋的正则表达式或200行代码?我看过Stackoverflow,尽管我发现";类似的";问题,没有解决特定的情况!

提前感谢

"Today we have an IKAR ME123 from Greece."
.replaceFirst("IKAR \w+","IKAR XXXX");
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 ) );
}
}

最新更新