Question

it's not a duplicate of Remove dash from a phone number maybe solution is here but i don't understand Can't remove dashes (-) from string

I have to remove al - (dash) from a String, alzo i have to remove " -" and "- " (all space near the dash) This don't work (do nothing)

toclean.replaceAll("[\\s\\-()]", "");
        toclean.replaceAll("[\\s\\- ()]", "");
        toclean.replaceAll("[\\s\\ -()]", "");

idea?

Was it helpful?

Solution

You want all spaces around the dash, whereas the regexes you've tried will remove all whitespace, dashes, and parentheses from your string. A regex to remove hyphens and the spaces around them would be:

"[ ]?-[ ]?"

If you want to remove any whitespace, you could use \s:

"\\s?-\\s?"

This will only remove the nearest whitespace before and after any hyphens (so, if you have two spaces before, it will only remove one).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top