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

  • A+
Category:Languages

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?

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: