Java: Removing trailing comma from comma separated string

Here's how:

str = str.replaceAll(", $", "");

This handles the empty list (empty string) gracefully, as opposed to lastIndexOf / substring solutions which requires special treatment of such case.

Note that this assumes that the string ends with , (comma followed by space).

If your input looks like… Use…
"a,b,c," ",$"
"a, b, c, " ", $"
"a , b , c , " " , $"
Any of the above "\\s*,\\s*$"

Full example

String str = "lorem, ipsum, dolor, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // "lorem, ipsum, dolor"

What does ", $" mean?

, $ is a regular expression that means "comma, followed by a space, followed by end of string". \s* means "0 or more white spaces".

Comments (2)

User avatar

Useful.

by Mythul |  Reply
User avatar

Awesome!! You have the best article on this topic. You're doing a great job. Thanks for sharing.

Cheers

by Pooja Malhothra |  Reply

Add comment