需求

在程序中,校验用户上传的数据是否包含有下表中的特殊字符
JAVA-处理不可见字符_数据

解决方法1
  • Java代码:
public static void main(String[] args) {
        String uploadDataVt = "upload data \u000B test";

        for (char i = 0; i < 32; i++) {
            Character ch = new Character(i);
            if (uploadDataVt.contains(ch.toString())) {
                // 上传的数据不合法,抛出提示信息。
                System.out.println("testObject1 contains " + ch.toString() + " character.");
            }
        }
    }
  • 运行结果:
testObject1 contains  character.

解决方法2

使用正则表达式"\\p{C}",将用户上传的数据中包含的特殊字符替换为空字符。

  • Java代码:
public static void main(String[] args) {

        String uploadDataAck = "upload data \u0006 test";
        String uploadDataHt = "upload data \t test";
        String uploadDataLf = "upload data \n test";
        String uploadDataVt = "upload data \u000B test";

        System.out.println("Before replace ACK:" + uploadDataAck);
        System.out.println("Before replace HT:" + uploadDataHt);
        System.out.println("Before replace LF:" + uploadDataLf);
        System.out.println("Before replace VT:" + uploadDataVt);

        uploadDataAck = uploadDataAck.replaceAll("\\p{C}", "");
        uploadDataHt = uploadDataHt.replaceAll("\\p{C}", "");
        uploadDataLf = uploadDataLf.replaceAll("\\p{C}", "");
        uploadDataVt = uploadDataVt.replaceAll("\\p{C}", "");

        System.out.println("After replace ACK:" + uploadDataAck);
        System.out.println("After replace HT:" + uploadDataHt);
        System.out.println("After replace LF:" + uploadDataLf);
        System.out.println("After replace VT:" + uploadDataVt);

    }
  • 运行结果:
Before replace ACK:upload data  test
Before replace HT:upload data 	 test
Before replace LF:upload data 
 test
Before replace VT:upload data  test
After replace ACK:upload data  test
After replace HT:upload data  test
After replace LF:upload data  test
After replace VT:upload data  test