简体   繁体   English

删除除Java中的选项卡之外的所有其他尾随空白字符

[英]Remove all other trailing whitespace characters except tab in Java

I know that removing whitespaces is as easy as String.trim(). 我知道删除空格就像String.trim()一样简单。 But my string contains tab (\\t) characters which I would like to keep. 但我的字符串包含我想保留的tab(\\ t)字符。

Example: 例:

"teststring\t\t\t     ".trimSpaceNotTab() => "teststring\t\t\t"

My current implementation is to use split(); 我目前的实现是使用split();

String[] arr = tabbedString.split("\t");

Then joining them somewhere as a string. 然后将它们作为字符串连接到某处。

I find this implementation slow and ugly. 我发现这个实现缓慢而丑陋。

Is there a better way in Java where I can retain the tabs? 在Java中有更好的方法可以保留标签吗?

How about 怎么样

tabbedString.replaceAll("[ \n\x0B\f\r]","")

Function used - String.replaceAll() 使用的函数 - String.replaceAll()

In case you'd like to also go for tabs and remove them, use a predefined character class \\s 如果您还想去标签并删除它们,请使用预定义的字符类\\s

Pattern Summary 模式摘要

浏览字符串并使用isSpaceChar询问每个Char是否有空格

使用替换所有空格但不替换制表符(\\ t)的正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM