santafebound santafebound - 10 days ago 4
Android Question

Remove all special characters from a string except for digits and the degree symbol?

I want to remove all special characters from a string except for digits and the degree symbol °. How can I do this using regex?

I know that .replaceAll("[^a-zA-Z0-9]+","") will remove all special characters, how do I put the degree symbol back in?

Answer

You may use \W and use a character class subtraction:

.replaceAll("[\\W_&&[^°]]+","")

enter image description here

Another way is to add the degree symbol to the negated character class you have since the negated character class matches all chars other than those in the character class:

.replaceAll("[^a-zA-Z0-9°]+","")
                        ^

enter image description here

Tested at: http://www.ocpsoft.org/tutorials/regular-expressions/java-visual-regex-tester/.

Comments