Removing all characters but letters in a string

时光怂恿深爱的人放手 提交于 2019-12-24 05:47:10

问题


If I have a string "ja.v_,a", how can I remove all non-letter characters to output "java"? I have tried str = str.replaceAll("\\W", "" ), but to no avail.


回答1:


Could you try this one?

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



回答2:


I would like to refer to this article and quote it:

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]+

So in your case it would be:

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

Where \p{L} is the Unicode definition of a "letter".




回答3:


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



回答4:


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

>java


来源:https://stackoverflow.com/questions/43263680/removing-all-characters-but-letters-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!