Java: Removing trailing comma from comma separated string
str = str.replaceAll(", $", "");
This handles the empty list (empty string) gracefully, as opposed to
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…|
|Any of the above||
String str = "lorem, ipsum, dolor, "; str = str.replaceAll(", $", ""); System.out.println(str); // "lorem, ipsum, dolor"
", $" mean?
, $ is a regular expression that means “comma, followed by a space, followed by end of string”.
\s* means “0 or more white spaces”.
Awesome!! You have the best article on this topic. You're doing a great job. Thanks for sharing.