How to remove control characters from java string?

前端 未结 7 2167
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 16:41

I have a string coming from UI that may contains control characters, and I want to remove all control characters except carriage returns, line feeds

7条回答
  •  既然无缘
    2020-12-15 16:49

    use these

    public static String removeNonAscii(String str)
    {
        return str.replaceAll("[^\\x00-\\x7F]", "");
    }
    
    public static String removeNonPrintable(String str) // All Control Char
    {
        return str.replaceAll("[\\p{C}]", "");
    }
    
    public static String removeSomeControlChar(String str) // Some Control Char
    {
        return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
    }
    
    public static String removeControlCharFull(String str)
    {
        return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
    }
    

提交回复
热议问题