Replace alphabet in a string using replace?

前端 未结 4 1592
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 14:20

I\'m wondering if I can use string.replace() to replace all alphabets in a string?

String sentence = \"hello world! 722\"
String str = sentence         


        
4条回答
  •  囚心锁ツ
    2020-12-19 14:28

    You replace using regular expressions with String#replaceAll. The pattern [a-zA-Z] will match all lowercase English letters (a-z) and all uppercase ones (A-Z). See the below code in action here.

    final String result = str.replaceAll("[a-zA-Z]","@"); 
    

    If you want to replace all alphabetical characters from all locales, use the pattern \p{L}. The documentation for Pattern states that:

    Both \p{L} and \p{IsL} denote the category of Unicode letters.

    See the below code in action here.

    final String result = str.replaceAll("\\p{L}", "@");
    

提交回复
热议问题