public static String replace(String input, String pattern, int occurence, String replacement){
String result = input;
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(result);
if(occurence == 0){
return result;
} else if(occurence == 1){
m.find();
result = result.substring(0,m.start()) + replacement + result.substring(m.end());
} else {
m.find();
int counter = 1;
try {
while((counter<occurence)&&m.find(m.start()+1)){
counter++;
}
result = result.substring(0,m.start()) + replacement + result.substring(m.end());
} catch(IllegalStateException ise){
throw new IllegalArgumentException("There are not this many occurences of the pattern in the String.");
}
}
return result;
}
私が正しく理解している場合、似たようなことをしているようです。
マッチャー/パターンシステムを使用すると、はるかに複雑な正規表現が使用できます。
String.indexOf(value、fromIndex)を繰り返し使用します。 – ControlAltDel