Replace alphabet in a string using replace?

2019-02-18 23:53发布

问题:

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

String sentence = "hello world! 722"
String str = sentence.replace("what to put here", "@");
//now str should be "@@@@@ @@@@@! 722"

In other words, how do I represent alphabetic characters?

Alternatives are welcomed too, unless too long.

回答1:

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.



回答2:

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 :)



回答3:

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



标签: java replace