解決方案:
String input = "Hello #'World'# , currently i am in #'world's'# best location.";
StringBuilder buf = new StringBuilder(input.length());
int start = 0, idx1, idx2;
while ((idx1 = input.indexOf("#'", start)) != -1) {
idx1 += 2;
if ((idx2 = input.indexOf("'#", idx1)) == -1)
break;
buf.append(input, start, idx1); // append text up to and incl. "#'"
for (; idx1 < idx2; idx1++)
buf.append('@'); // append replacement characters
start = idx2 + 2;
buf.append(input, idx2, start); // append "'#"
}
buf.append(input, start, input.length()); // append text after last "'#"
String output = buf.toString();
System.out.println(input);
System.out.println(output);
輸出
Hello #'World'# , currently i am in #'world's'# best location.
Hello #'@@@@@'# , currently i am in #'@@@@@@@'# best location.
[學習正則表達式]的可能重複(http://stackoverflow.com/questions/4736/learning-regular-expressions) –
@AndyBrown,以及,替換依賴於(長度)匹配,所以這不是一個簡單的調用'replaceAll'。 – aioobe
你的意思是它必須使用'replaceAll()',還是可以使用正則表達式來查找要替換的字符串?它絕對必須是正則表達式嗎? – Andreas