I believe the question is "how to remove a value from the list", but only the exact value (e.g. 2 not 12, 13 not 413), and to shorten the list, i.e. to remove the preceding or following comma, if any, but not both.
Short Answer:
String x = Pattern.quote(textToRemove);
Pattern p = Pattern.compile("^"+x+"$|^"+x+",|,"+x+"$|,"+x+"(?=,)");
String output = p.matcher(input).replaceAll(""); // or replaceFirst
Examples:
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
Code:
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 + '"');
}
Test:
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" );
}
Output:
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" : ""