我認爲問題是「如何從列表中刪除一個值」,但只有值(例如2而不是12,13不是413),並且縮小列表,即刪除前面或後面的逗號,如果有的話,但不是兩者。
答案很簡單:
String x = Pattern.quote(textToRemove);
Pattern p = Pattern.compile("^"+x+"$|^"+x+",|,"+x+"$|,"+x+"(?=,)");
String output = p.matcher(input).replaceAll(""); // or replaceFirst
例子:
Input: "6,20,9,10,19,101,5,3,1,2"
Remove "2": "6,20,9,10,19,101,5,3,1" -- last value, don't remove 20
Remove "20": "6,9,10,19,101,5,3,1,2" -- middle value
Remove "1": "6,20,9,10,19,101,5,3,2" -- don't remove 10, 19, or 101
Remove "10": "6,20,9,19,101,5,3,1,2" -- don't remove 101
Remove "6": "20,9,10,19,101,5,3,1,2" -- first value
Remove "77": "6,20,9,10,19,101,5,3,1,2" -- nothing removed
Input: "6"
Remove "6": "" -- only value
代碼:
private static void test(String input, String textToRemove) {
String rmv = Pattern.quote(textToRemove);
Pattern p = Pattern.compile("^" + rmv + "$" + // matches only value
"|^" + rmv + "," + // matches first value + ','
"|," + rmv + "$" + // matches ',' + last value
"|," + rmv + "(?=,)"); // matches ',' + middle value (+ ',')
String output = p.matcher(input).replaceAll(""); // or replaceFirst
System.out.printf("Remove %-4s from %-26s: %s%n",
'"' + textToRemove + '"',
'"' + input + '"',
'"' + output + '"');
}
測試:
public static void main(String[] args) throws Exception {
//
test("6,20,9,10,19,101,5,3,1,2", "2");
test("6,20,9,10,19,101,5,3,1,2", "20");
test("6,20,9,10,19,101,5,3,1,2", "1");
test("6,20,9,10,19,101,5,3,1,2", "10");
test("6,20,9,10,19,101,5,3,1,2", "6");
test("6,20,9,10,19,101,5,3,1,2", "77");
test("6" , "6");
}
輸出:
Remove "2" from "6,20,9,10,19,101,5,3,1,2": "6,20,9,10,19,101,5,3,1"
Remove "20" from "6,20,9,10,19,101,5,3,1,2": "6,9,10,19,101,5,3,1,2"
Remove "1" from "6,20,9,10,19,101,5,3,1,2": "6,20,9,10,19,101,5,3,2"
Remove "10" from "6,20,9,10,19,101,5,3,1,2": "6,20,9,19,101,5,3,1,2"
Remove "6" from "6,20,9,10,19,101,5,3,1,2": "20,9,10,19,101,5,3,1,2"
Remove "77" from "6,20,9,10,19,101,5,3,1,2": "6,20,9,10,19,101,5,3,1,2"
Remove "6" from "6" : ""
但在這種情況下,我必須做一個循環找元素,將其刪除,最後加入的所有元素重新打造的字符串。 。我認爲replace()方法更快或者沒有? –
取決於你想要做什麼。字符串操作對於運行時並不是很好,所以我明確表示只有在不受約束的情況下才是解決方案。如果你可以詳細說明你的約束條件,我相信可以找到更好的解決方案。 –
我問實際上是否有一個特定的正則表達式來幫助我在這種情況下,或者如果我錯了我貼的代碼.. –