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 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}", "@");