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.
Asked
Active
Viewed 5,543 times
2 Answers
2
You can do it like this:
str.matches("[a-zA-Z\\s\'\"]+");
You said preferably no REGEX, but you wanted an elegant way. In my opinion this would be an easy, short and elegant way to get what you want.

user3437460
- 17,253
- 15
- 58
- 106
0
If you do not want REGEX, you may check character by character in the String:
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

user3437460
- 17,253
- 15
- 58
- 106
-
Thats exactly what I was considering to do, but I think I'll go with the regex way anyway, because it is that much shorter. I found this video https://www.youtube.com/watch?v=s_PfopWcMwI&ab_channel=DerekBanas and it explained enough of regex for me to more or less understand the answer I accepted – Sander Feb 27 '16 at 19:21