I\'m wondering if I can use string.replace()
to replace all alphabets in a string?
String sentence = \"hello world! 722\"
String str = sentence
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
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}", "@");
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.
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 :)