这是一个简单的解决方案。但是这段代码是可重用的。你可以随心所欲地使用它。
String original = "118|142|4000000|99|8|1372055573|0";
String toFind = "4000000|99|8|1372055573|0";
String toReplace = "2900|99|20|99999999|0";
int ocurrence = 1;
String replaced = replaceNthOcurrence(original, toFind, toReplace,ocurrence);
System.out.println(replaced);
的功能代码replaceNthOcurrence
:
public static String replaceNthOcurrence(String str, String toFind, String toReplace, int ocurrence) {
Pattern p = Pattern.compile(Pattern.quote(toFind));
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer(str);
int i = 0;
while (m.find()) {
if (++i == ocurrence) { sb.replace(m.start(), m.end(), toReplace); break; }
}
return sb.toString();
}