I have not come across any documentation on this.
Is there a way to find out if a string consists of any non-printable characters in Scala?
I have not come across any documentation on this.
Is there a way to find out if a string consists of any non-printable characters in Scala?
Here's the accepted answer to this question, translated into idiomatic Scala.
import java.awt.event.KeyEvent
def isPrintableChar(c: Char) =
!Character.isISOControl(c) &&
c != KeyEvent.CHAR_UNDEFINED &&
Option(Character.UnicodeBlock.of(c)).fold(false)(
_ ne Character.UnicodeBlock.SPECIALS)
The following method detects non-printable ASCII characters. A simple Regex pattern is used to look for any characters outside of the 0x20-0x7E
ASCII range:
def hasNonprintableAsciiChar(s: String): Boolean = {
val pattern = """[^\x20-\x7E]+""".r
pattern.findFirstMatchIn(s) match {
case Some(_) => true
case None => false
}
}
hasNonprintableAsciiChar("abc-xyz-123")
// res1: Boolean = false
hasNonprintableAsciiChar("abc¥xyz£123")
// res2: Boolean = true
hasNonprintableAsciiChar("abc123" + '\u200B')
// res3: Boolean = true