JAVA-處理不可見字符


需求

在程序中,校驗用戶上傳的數據是否包含有下表中的特殊字符
image

解決方法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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM