Reputation: 45
I have a question, and I'm sure there is a relatively simple answer to this, but at the moment I'm having a massive brain fart and can't seem to think of an elegant solution that doesn't involve a ridiculous myriad of if statements.
Basically, I have a web page that is dynamically updating the users present into a string, stylised as such
User1, User2, User3, User4
However, when I delete one of these users, from a different location, they are removed from the list, but I'm left with the following
Beginning
, User2, User3, User4
Middle
User1, , User3, User4
End
User1, User2, User3,
If anyone knows of a relatively easy way to remove these unwanted commas, that would be really helpful; it's been bugging me for hours.
Upvotes: 3
Views: 3335
Reputation: 31467
I would do a split and then a join.
With Guava:
final Iterable<String> fields = Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.split(data);
final String trimmedData = Joiner.on(",").join(fields);
With this you can even validate the input fields with Iterables.filter
if you want.
Upvotes: 1
Reputation: 25613
",User1, , User3, User4,".replaceAll("[\\s],|,$|^,", "");
->
User1, User3, User4
Upvotes: 1
Reputation: 4812
You could simply try:
String s = "User1, , User2, User3, ,...;
s = s.replaceAll(", ,", ",");
Upvotes: 1
Reputation: 15675
You could match ,$
, ^,
and , ,
with a regex and replace it with empty
Upvotes: 6