Reputation: 746
I want to check if String contains only Latin letters but also can contains numbers and other symbols like: _/+), etc.
String utm_source=google
should pass, utm_source=google&2019_and_2020!
should pass too. But utm_ресурс=google
should not pass (coz cyrillic letters). I know code with regex, but how can i do it without using regex and classic for loop, maybe with Streams and Character class?
Upvotes: 0
Views: 1151
Reputation: 32012
Less of a neat single line approach but really all you need to do is check whether the numeric value of the character is within certain limits like so:
public boolean isQwerty(String text) {
int length = text.length();
for(int i = 0; i < length; i++) {
char character = text.charAt(i);
int ascii = character;
if(ascii<32||ascii>126) {
return false;
}
}
return true;
}
Test Run
ä
returns false
abc
returns true
Upvotes: 0
Reputation: 109613
For restricted "latin" (no é etcetera), it must be either US-ASCII (7 bits), or ISO-8859-1 but without accented letters.
boolean isBasicLatin(String s) {
return s.codePoints().allMatch(cp -> cp < 128 || (cp < 256 && !isLetter(cp)));
}
Upvotes: 2
Reputation: 328
Use this code
public static boolean isValidUsAscii (String s) {
return Charset.forName("US-ASCII").newEncoder().canEncode(s);
}
Upvotes: 3