Removing special characters from a string

前端 未结 3 1543
小鲜肉
小鲜肉 2021-01-23 13:23

I have a string in my Java program which is read from database.

This may contain special characters in between as below:

相关标签:
3条回答
  • 2021-01-23 14:00

    You can use String#replaceAll:

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

    The ^ is saying: "Keep all chars that are not in the specified ranges inside the square brackets".

    0 讨论(0)
  • 2021-01-23 14:08

    Try the regex,

    String result= yourString.replaceAll("[^a-zA-Z0-9]+","");
    

    That gives you the result with only Alpha Numeric.

    If you want only Alphabets

    String resultWithAlphabetsOnly= yourString.replaceAll("[^a-zA-Z]+",""); 
    
    0 讨论(0)
  • 2021-01-23 14:13

    I would write

    theString.replaceAll("\\W","");
    

    This will remove everything except for letters, numbers and underscores.

    0 讨论(0)
提交回复
热议问题