2015-09-07 64 views
-2

兩個給定的格局與@所有字符我有一個​​字符串像這樣有沒有一種方法,以取代在Java

Hello #'World'# , currently i am in #'world's'# best location. 

我需要使用正則表達式中的Java #''#之間,以取代這一切的字符我需要一個最終的字符串應該是這種格式不使用正則表達式

Hello #'@@@@@'# , currently i am in #'@@@@@@@'# best location. 
+1

[學習正則表達式]的可能重複(http://stackoverflow.com/questions/4736/learning-regular-expressions) –

+1

@AndyBrown,以及,替換依賴於(長度)匹配,所以這不是一個簡單的調用'replaceAll'。 – aioobe

+0

你的意思是它必須使用'replaceAll()',還是可以使用正則表達式來查找要替換的字符串?它絕對必須是正則表達式嗎? – Andreas

回答

1

解決方案:

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. 
+0

你很聰明。 –

相關問題