比賽第一,如果字符串爲您選擇結束或不喜歡下面 -
if (value.endsWith("\'") || value.endsWith("--") || value.endsWith("-"))
等你的選擇。
,如果再從字符串中刪除最後一個字符,這僅是這樣 -
value = value.substring(0, value.length()-1);
檢查下面的示例代碼,以更好地理解 -
String value = "!lovely?! hi!?'";
if (value.endsWith("\'") || value.endsWith("--") || value.endsWith("-")) {
value = value.substring(0, value.length()-1);
}
System.out.println(value);
如果你想使用Java正則表達式進行比較然後以這種方式使用 -
if(value.matches(".*[' -- - ly ]$"))
- 。*用於以多個字符開頭。
- [' - - ly]給你你的選擇的實際比較。爲每個角色提供空間選項。
- $ for String以其中任何一個結束。
以這種方式,您可以使用正則表達式來比較字符串。
更具體地說,如果要從字符串中刪除最後一個,兩個,三個和四個字符,則可以使用此最佳方法。
//provide only one character String that you want to check and remove
if (value.matches(".*[' - ?]$")){
value = value.substring(0, value.length()-1);
}
//provide two character String that you want to check and remove
if (value.matches(".*[-- ly ab cd ef]$")){
value = value.substring(0, value.length()-2);
}
//provide three character String that you want to check and remove
if (value.matches(".*[-- lyy abc def ghi]$")){
value = value.substring(0, value.length()-3);
}
//provide four character String that you want to check and remove
if (value.matches(".*[-- lyyy abcd efgh ijkl]$")){
value = value.substring(0, value.length()-4);
}
來源
2016-12-07 04:52:29
kit
您正在將'(...)'(或甚至非捕獲分組''(?:...)')與字符類'[...]''混合起來。 'value.replaceAll(「(ly |!| \?|')+ $」,「」);'應該有效。 (注意你也需要將問號轉義爲'\?',因爲它在正則表達式中有特殊意義)。另外,如果你不想刪除多個後綴,'+'是額外的。 – Amadan
您對'replaceAll'的調用不包括您提到的所有結尾。另外,看起來你想從結尾移除結尾,並且只要你找到新的令牌,就繼續這樣做。這聽起來像解析器的工作。 –
@Amadan我嘗試了你的建議並編輯了問題 – user2769614