2
0

More than 3 years have passed since last update.

文字列からASCIIコードの制御文字を削除する

Last updated at Posted at 2020-03-13

LT;DR

Hexをbyte配列に変換してnew String(byte[])したら0x00とか0x01とか入ってきてムキーってなったので調べた。

ASCII制御文字を文字列から除去する。

replaseAsciiCC.java
// hexからbyteに変換するのに必要。
import javax.xml.bind.DatatypeConverter;

// class定義とかmethod定義とか略

String hex = "0100313233343536373839302D5E5C";  // 先頭4byteが制御文字

byte[] hexFromByte = DatatypeConverter.parseHexBinary(hex);
String strFromByte = new String(hexFromByte);

String resultStr strFromByte.replaceAll("\\p{C}", ""));

// 制御文字が消えて"1234567890-^\"って出力されるはず。
System.out.println(resultStr);

なぜ"\p{C}"でいいのかはこの辺。
https://regular-expressions.mobi/unicode.html?wlr=1

改行コードも除去されるので注意。
Java以外の言語で使えるかは解らぬ。

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