简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM