LoginSignup
5
4

More than 5 years have passed since last update.

マルチバイト文字をエスケープする

Last updated at Posted at 2012-09-26

1行で済んだ。考えすぎてた。

def str = 'Groovyは、JVM上の言語です。'

str = str.replaceAll(/[^\x00-\x7f]/){'\\u'+Integer.toHexString((int)it)}
assert str == 'Groovy\\u306f\\u3001JVM\\u4e0a\\u306e\\u8a00\\u8a9e\\u3067\\u3059\\u3002'

ああ、でも、これだとサロゲートペア文字のエスケープができない。
commons.lang.StringEscapeUtilsを使う。

import org.apache.commons.lang.StringEscapeUtils
@Grab('commons-lang:commons-lang:latest.release')

def str = 'Groovyは、JVM上の言語です。'
str = str.replaceAll(/[^\x00-\x7f]+/){ StringEscapeUtils.escapeJava(it) }
assert str == 'Groovy\\u306F\\u3001JVM\\u4E0A\\u306E\\u8A00\\u8A9E\\u3067\\u3059\\u3002'
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4