How to check if a String contains only ASCII?

TambourineMan picture TambourineMan · Aug 27, 2010 · Viewed 98.2k times · Source

The call Character.isLetter(c) returns true if the character is a letter. But is there a way to quickly find if a String only contains the base characters of ASCII?

Answer

ColinD picture ColinD · Aug 27, 2010

From Guava 19.0 onward, you may use:

boolean isAscii = CharMatcher.ascii().matchesAllOf(someString);

This uses the matchesAllOf(someString) method which relies on the factory method ascii() rather than the now deprecated ASCII singleton.

Here ASCII includes all ASCII characters including the non-printable characters lower than 0x20 (space) such as tabs, line-feed / return but also BEL with code 0x07 and DEL with code 0x7F.

This code incorrectly uses characters rather than code points, even if code points are indicated in the comments of earlier versions. Fortunately, the characters required to create code point with a value of U+010000 or over uses two surrogate characters with a value outside of the ASCII range. So the method still succeeds in testing for ASCII, even for strings containing emoji's.

For earlier Guava versions without the ascii() method you may write:

boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);