删除字符串中除字母以外的所有字符

Removing all characters but letters in a string

如果我有一个字符串"ja.v_,a",我如何去除所有非字母字符以输出"java"?我试过 str = str.replaceAll("\W", "" ),但没有用。

String s = "ja.v_,a";
s = s.replaceAll("[^a-z]", "");
System.out.println(s);

>java

你能试试这个吗?

System.out.println("ja.v_,a".replaceAll("[^a-zA-Z]", "")) //java

我想参考this article并引用它:

Regex examples and tutorials always give you the [a-zA-Z0-9]+ regex to "validate alphanumeric input". It is built-in in many validation frameworks. And it is so utterly wrong. This is a regex that must never appear anywhere in your code, unless you have a pretty good explanation. Yet, the example is ubiquitous. Instead, the right regex is [\p{L}0-9]+

所以在你的情况下会是:

str.replaceAll("[^\p{L}]", "");
System.out.println("ja.v_,a".replaceAll("[^\p{L}]", ""));
System.out.println("сл-=о-_=во!".replaceAll("[^\p{L}]", ""));

其中 \p{L} 是 "letter" 的 Unicode 定义。

String test= "ja.v_,a";

int len=test.length();

String alphaString="";

for(int i=0; i<len; i++){
     if (Character.isLetter(test.charAt(i))) {
         alphaString=alphaString+test.charAt(i);
     }
}

System.out.println(alphaString);