简体   繁体   中英

How to check if String contains Latin letters without regex

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?

Use this code

public static boolean isValidUsAscii (String s) {
        return Charset.forName("US-ASCII").newEncoder().canEncode(s);
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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