简体   繁体   English

检查字符串是否只包含字母空格和引号(最好不包含正则表达式)

[英]check whether a string contains only letters spaces and quotes (preferably no regex)

I am trying to check if a string has only letters (both uppercase and lowercase), spaces and quotes (both double and single) in it. 我试图检查一个字符串是否只有字母(大写和小写),空格和引号(包括双和单)。 I can't quite come up with an elegant way of doing this. 我无法想出一个优雅的方式来做到这一点。 The only thing I could come up with is making a list of the allowed characters and checking if each character of the string is in that list. 我唯一能想到的是制作一个允许的字符列表,并检查字符串的每个字符是否在该列表中。

You can do it like this: 你可以这样做:

str.matches("[a-zA-Z\\s\'\"]+");

You said preferably no REGEX, but you wanted an elegant way. 你说最好没有REGEX,但你想要一个优雅的方式。 In my opinion this would be an easy, short and elegant way to get what you want. 在我看来,这将是一种简单,简洁和优雅的方式来获得你想要的东西。

If you do not want REGEX, you may check character by character in the String: 如果您不想要REGEX,可以在字符串中逐字符检查:

public static boolean onlyLetterSpaceQuotes(String str){
    for(int x=0; x<str.length(); x++){
        char ch = str.charAt(x);
        if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ' ' 
            || ch == '\'' || ch == '\"'))
            return false;               
    }
    return true;            
}

Test: 测试:

System.out.println(onlyLetterSpaceQuotes("abc \"A\'BC"));
System.out.println(onlyLetterSpaceQuotes("abc \"A\'BC123")); 

Output: 输出:

true
false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM