java 字符串只包含字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13201497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
string contains only alphabets
提问by Mary
I'm new to Java programming and I need help. Create a table of String and the user gives the size. Subsequently, the user gives String. I want to print the characters but without the characters which are not letters of the alphabet (eg. java!4 --> java, ja/?,.va --> java)
我是 Java 编程新手,需要帮助。创建一个字符串表,用户给出大小。随后,用户给出字符串。我想打印字符但没有不是字母的字符(例如 java!4 --> java, ja/?,.va --> java)
public static void main (String[] args) {
String[] x = new String[size];
int size;
String str= "";
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Give me size: ");
size = Integer.parseInt(input.readLine());
for(int i=0; i<size; i++){
System.out.print("Give me a String: ");
str = input.readLine();
x[i]=str;
}
}
I am looking on the internet for this code:
我正在互联网上寻找此代码:
if (str.matches("[a-zA-Z]")){
System.out.println(str);
}
采纳答案by Luiggi Mendoza
Since you're new to programming and don't want to involve in the RegEx world (yet), you can create a method that returns a String
with letters only:
由于您是编程新手并且不想参与 RegEx 世界(还),您可以创建一个String
仅返回带字母的方法:
public String getStringOfLettersOnly(String s) {
//using a StringBuilder instead of concatenate Strings
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i))) {
//adding data into the StringBuilder
sb.append(s.charAt(i));
}
}
//return the String contained in the StringBuilder
return sb.toString();
}
回答by asthasr
You can do this with a very simple regular expression: s/[^A-z]//g
. This will substitute nothing for all characters in the string which aren't in the range A-z
, which encapsulates all letters (upper and lowercase). Simply do new_string = old_string.replaceAll("[^A-z]", "");
.
你可以用一个很简单的正则表达式做到这一点: s/[^A-z]//g
。这不会替换字符串中不在 range 中的A-z
所有字符,它封装了所有字母(大写和小写)。简单地做new_string = old_string.replaceAll("[^A-z]", "");
。
回答by PermGenError
you can check if a string
has only alaphabets
with regex.
below is the sample code
您可以检查 astring
是否只有alaphabets
正则表达式。下面是示例代码
String word = "java";
Pattern pattern = Pattern.compiles("[a-zA-Z]+");
Matcher matcher = pattern.matcher(word);
System.out.println(pattern.find());
Or you can use String.matches(regex)
from String APIread about REGEX in Java
或者你可以使用String.matches(regex)
从字符串API了解Java中REGEX