Remove last comma from string that doesn't end with comma in Java 8

Sahil :

I have input string:

String myString = "test, test1, must not be null";

I want to remove last comma in this string

Expected output:

test, test1 must not be null

Any idea if this can be done using StringUtils?

Tim Biegeleisen :

Here is one option which uses a negative lookahead to target the final comma in the string:

String myString = "test, test1, must not be null";
myString = myString.replaceAll(",(?!.*,)", "");
System.out.println(myString);

test, test1 must not be null

Demo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110660&siteId=1