简体   繁体   中英

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?

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

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

在此处输入图片说明

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°]+","")
                        ^

在此处输入图片说明

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

You can use unicode character: ° is . So your regex can look like this:

[^a-zA-Z0-9\\u00b0]+

Example: https://regex101.com/r/ZgGdHj/3

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