Ali Gajani
Ali Gajani

Reputation: 15089

How do I make sure the replaceAll() doesn't leave my String with many spaces?

I am doing this on my String right now: .replaceAll("[^A-Za-z0-9]"," ").toLowerCase()

Gives me something like this:

yg jarang orang perasan  pernah tak korang perasan dlm mickey mouse dulu      http

I want to make sure those unnecessary whitespaces are minimized.

I tried .trim() but to no avail.

Upvotes: 0

Views: 28

Answers (2)

Denis Kulagin
Denis Kulagin

Reputation: 8947

Try this:

.replaceAll("[^A-Za-z0-9]+"," ").toLowerCase()

More:

trim() deletes all whitespace characters before and after your string. It doesn't touch ones in the middle.

Upvotes: 1

rgettman
rgettman

Reputation: 178363

You can add the + metacharacter, which means "one or more matches".

.replaceAll("[^A-Za-z0-9]+"," ").toLowerCase()

This will replace one or more non-letter, non-punctuation characters with exactly one space.

Upvotes: 3

Related Questions