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

I am currently working with scanners and analyzers and need a parser that accepts characters that are ASCII letters, so I cannot use it char.isLetter.

I myself came up with two solutions. I do not like both of them.

Regex

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

It seems rather "redundant" to test such a simple thing with regex.

Range check

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

In my opinion, this would be a way to go in Java. But this is not entirely clear.

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

+5
source share
4 answers

, Char.isLetter, ASCII. 7- ASCII?

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

ASCII, -, :

def isAscii(c: Char) = c.toInt <= 127
+13

, , " ASCII" . :.

object Program extends App {
  implicit class CharProperties(val ch: Char) extends AnyVal {
    def isASCIILetter: Boolean =
      (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
  }
  println('x'.isASCIILetter)
  println('0'.isASCIILetter)
}

ASCII :

object Program extends App {
  object CharProperties {
    val ASCIILetters = ('a' to 'z').toSet ++ ('A' to 'Z').toSet
  }
  implicit class CharProperties(val ch: Char) extends AnyVal {
    def isASCIILetter: Boolean =
      CharProperties.ASCIILetters.contains(ch)
  }
  println('x'.isASCIILetter)
  println('0'.isASCIILetter)
}

, , ( ).

+2

:

def letter = elem("ascii letter", c => ('a' to 'z') ++ ('A' to 'Z') contains c)

, .

, ++, :

c => ('a' to 'z') union ('A' to 'Z') contains c
0

Another - well-elegant solution may use min / max:

c => 'A'.max(c.toUpper) == 'Z'.min(c.toUpper)

or

c => 'A'.max(c) == 'Z'.min(c) || 'a'.max(c) == 'z'.min(c)
-1
source

All Articles