Replace alphabet in a string using replace?

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

    You can use the following (regular expression):

        String test = "hello world! 722";
        System.out.println(test);
        String testNew = test.replaceAll("(\\p{Alpha})", "@");
        System.out.println(testNew);
    

    You can read all about it in here: http://docs.oracle.com/javase/tutorial/essential/regex/index.html

    0 讨论(0)
  • 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}", "@");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 14:44

    Use String#replaceAll that takes a Regex:

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

    Note that String#replace takes a String as argument and not a Regex. If you still want to use it, you should loop on the String char-by-char and check whether this char is in the range [a-z] or [A-Z] and replace it with @. But if it's not a homework and you can use replaceAll, use it :)

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