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
One option is to use a combination of CharMatcher
s:
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.