I have a string coming from a ui that contains control characters. Such as line feeds and carrage returns.
我有一个来自ui的字符串,其中包含控制字符。例如换行和回车。
I would like to do something like this:
我想做这样的事情:
String input = uiString.replaceAll(<regex for all control characters> , "")
Surely this has been done before!?
当然这已经完成了!?
2 个解决方案
#1
15
Something like this should do the trick:
像这样的东西应该做的伎俩:
String newString = oldString.replaceAll("[\u0000-\u001f]", "");
#2
22
Using Guava, probably more efficient than using the full regex engine, and certainly more readable...
使用Guava,可能比使用完整的正则表达式引擎更有效,当然更具可读性......
return CharMatcher.JAVA_ISO_CONTROL.removeFrom(string);
Alternately, just using regexes, albeit not quite as readably or efficiently...
或者,只使用正则表达式,尽管不是那么可读或有效......
return string.replaceAll("\\p{Cntrl}", "");
#1
15
Something like this should do the trick:
像这样的东西应该做的伎俩:
String newString = oldString.replaceAll("[\u0000-\u001f]", "");
#2
22
Using Guava, probably more efficient than using the full regex engine, and certainly more readable...
使用Guava,可能比使用完整的正则表达式引擎更有效,当然更具可读性......
return CharMatcher.JAVA_ISO_CONTROL.removeFrom(string);
Alternately, just using regexes, albeit not quite as readably or efficiently...
或者,只使用正则表达式,尽管不是那么可读或有效......
return string.replaceAll("\\p{Cntrl}", "");