I'd like to know how to get rid of all non-alphabet in a string please.
I have a String s, where many non-alphabetical characters can be inside. For instance, space, dots, slashes, and any other crazy stuff that are not from a, b, c ... z and not from A, B, C ... Z.
I just want to retain those a, b, c ... z and A, B, C ... Z.
Hence, I wrote:
private static String getGoodString(String s) {
return s.replaceAll("[^a-zA-Z]", "");
}
This is actually working, quite happy.
However, SonarQube is complaining with:
Refactor this code to use a "static final" Pattern.
Replace these character ranges with Unicode-aware character classes.
How may I achieve the same (get ride of any non-alphabet), while making SonarQube very happy at the same time please?
Try using this version:
// inside your class
private static final Pattern p = Pattern.compile("[^\\p{Alpha}]");
private static String getGoodString(String s) {
return p.matcher(s).replaceAll("");
}
Here I am using a static final Pattern
. Also, the regex \p{Alpha}
is the Unicode version for matching any letter character.