Replace alphabet in a string using replace?

前端 未结 4 1619
爱一瞬间的悲伤
爱一瞬间的悲伤 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:29

    Java's String#replaceAll takes a regex string as argument. Tha being said, [a-ZA-Z] matches any char from a to z (lowercase) and A to Z (uppercase) and that seems to be what you need.

    String sentence = "hello world! 722";
    String str = sentence.replaceAll("[a-zA-Z]", "@");
    System.out.println(str); // "@@@@@ @@@@@! 722"
    

    See demo here.

提交回复
热议问题