How to remove control characters from java string?

前端 未结 7 2168
没有蜡笔的小新
没有蜡笔的小新 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:50

    One option is to use a combination of CharMatchers:

    CharMatcher charsToPreserve = CharMatcher.anyOf("\r\n\t");
    CharMatcher allButPreserved = charsToPreserve.negate();
    CharMatcher controlCharactersToRemove = CharMatcher.JAVA_ISO_CONTROL.and(allButPreserved);
    

    Then use removeFrom as before. I don't know how efficient it is, but it's at least simple.


    As noted in edits, JAVA_ISO_CONTROL is now deprecated in Guava; the javaIsoControl() method is preferred.

提交回复
热议问题