3
我需要替換第五個之後的所有逗號。所以如果一個String包含10個commans,我只想留下前5個,並且刪除所有隨後的逗號。如何替換字符串中第n個字符的發生?
我該怎麼做?
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = sentence.replaceAll(",[6]","");
我需要替換第五個之後的所有逗號。所以如果一個String包含10個commans,我只想留下前5個,並且刪除所有隨後的逗號。如何替換字符串中第n個字符的發生?
我該怎麼做?
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = sentence.replaceAll(",[6]","");
剛剛從一開始就高達5日逗號捕獲所有的字符,並且匹配使用交替操作|
所有剩餘的逗號。所以,
|
應該匹配所有剩餘的逗號。用$1
替換所有匹配的字符將會給你想要的輸出。
sentence.replaceAll("^((?:[^,]*,){5})|,", "$1");
如果你想知道如何不使用正則表達式解決這個問題...有圖書館,可以使您的生活更輕鬆,但這裏是浮現在腦海的第一個念頭。
public String replaceSpecificCharAfter(String input, char find, int deleteAfter){
char[] inputArray = input.toCharArray();
String output = "";
int count = 0;
for(int i=0; i <inputArray.length; i++){
char letter = inputArray[i];
if(letter == find){
count++;
if (count <= deleteAfter){
output += letter;
}
}
else{
output += letter;
}
}
return output;
}
,那麼你會調用該函數,像這樣:
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = replaceSpecificCharAfter(sentence, ',', 6);
這工作,但正則表達式是真的不適合工作的工具在這裏。它們是通常只有原作者才能理解的緩慢,難看的代碼,並且很容易讓它們稍微錯誤。 – cderwin
作爲魅力!不知道爲什麼和如何,但它完成了工作,謝謝 – Emily
@cderwin如果它很醜,那麼爲什麼所有的語言都添加它.. –