0

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?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
Garipaso
  • 391
  • 2
  • 8
  • 22
  • https://stackoverflow.com/questions/2485636/how-to-detect-and-replace-non-printable-characters-in-a-string-using-java – pedrofurla Sep 08 '17 at 15:57

2 Answers2

2

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)
jwvh
  • 50,871
  • 7
  • 38
  • 64
1

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
Leo C
  • 22,006
  • 3
  • 26
  • 39
  • Unicode has many other non-printable characters. for example http://www.fileformat.info/info/unicode/char/200B/index.htm – pedrofurla Sep 08 '17 at 19:15
  • 2
    The suggested method considers anything outside of the printable ASCII char range non-printable hence should be able to detect non-printable Unicode characters. e.g. `hasNonprintableAsciiChar("abc123" + 0x200B.toChar)` would return `true`. – Leo C Sep 08 '17 at 20:23
  • thankyou very much for all the responses provided, they are all help ful – Garipaso Sep 09 '17 at 16:30