r0estir0bbe r0estir0bbe - 1 year ago 76
Scala Question

What is an elegant way to check if a character is an ASCII letter (a-Z) in Scala?

I am currently working with Scanners and Parsers and need a Parser that accepts characters that are ASCII letters - so I can't use


I came up with two solutions myself. I don't like both of them.


def letter = elem("ascii letter", _.toString.matches("""[a-zA-Z]"""))

This seems rather "overkill" to check such a simple thing with a regex.

Range check

def letter = elem("ascii letter", c => ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))

In my opinion, this would be the way to go in Java. But it's not really readable.

Is there a cleaner, more Scala-like solution to this problem? I do not really worry about performance, as it doesn't matter in this case.

Answer Source

You say you can't use Char.isLetter because you only want ASCII letters. Why not just restrict it to the 7-bit ASCII character range?

def isAsciiLetter(c: Char) = c.isLetter && c <= 'z'

If the reader wants to check for ASCII including non-letters then:

def isAscii(c: Char) = c <= '~'