2017-09-08 13 views
0

私はこれに関するドキュメントを見つけていません。Scalaで印刷できない文字を検出する

文字列がScalaの印刷できない文字で構成されているかどうかを調べる方法はありますか?

+0

https://stackoverflow.com/questions/2485636/how-to-detect-and-replace-non-printable-characters-in-a-string-using-java – pedrofurla

答えて

0

以下の方法はnon-printable ASCII charactersを検出します。簡単な正規表現パターンは0x20-0x7E ASCIIの範囲外の任意の文字を探すために使用されます。

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 
+0

Unicodeは、他の多くの非を持っています印刷可能な文字。例:http://www.fileformat.info/info/unicode/char/200B/index.htm – pedrofurla

+1

提案された方法は、印刷可能なASCII文字範囲外のものを印刷不可能とみなし、印刷不可能なUnicode文字を検出できるはずです。例えば'hasNonprintableAsciiChar(" abc123 "+ 0x200B.toChar)'は 'true'を返します。 –

+0

お返事ありがとうございました。回答はすべて提供されています – Garipaso

1

ここでは慣用的なスカラ座に翻訳this questionへの受け入れ答えは、です。

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)