Reputation: 35
im trying to validate string to match all ascii chars on java with regex. if there is only ascii chars return true, if there is even single char which is not ascii char return false.
i tried the following:
Pattern.compile("[^ -~\\r\\n\\t]+").matcher(password).find();
and also tried this:
Pattern.compile("[^\\Q A-Za-z0-9!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\\E]").matcher(password).find();
but it didnt worked. the string im trying to validate:
"abตcdefgh12+"
but both codes return to me true, which means its contains only ascii chars which is not... i want that this string will return false.
thanks!
Upvotes: 0
Views: 197
Reputation: 5341
Try this:
public static boolean isPureAscii(String s) {
return Charset.forName("US-ASCII").newEncoder().canEncode(s);
}
Reference: https://docs.oracle.com/javase/1.5.0/docs/api/java/nio/charset/Charset.html
Upvotes: 2