如何删除一个字符串在Java中,只有尾部的空格,并保持领先的空间? [英] How to remove only trailing spaces of a string in Java and keep leading spaces?

查看:477
本文介绍了如何删除一个字符串在Java中,只有尾部的空格,并保持领先的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的<一个href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim%28%29"><$c$c>trim()功能将同时删除尾随和前导空格,但是,如果我只是想删除一个字符串的尾部空间,我该怎么办呢?

The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?

谢谢!

推荐答案

使用常规的前pression \ S + $ ,可以更换所有尾随空格字符(包括空格和制表符)没事()。

Using the regular expression \s+$, you can replace all trailing space characters (includes space and tab characters) with nothing ("").

final String text = "  foo   ";
System.out.println(text.replaceFirst("\\s+$", ""));

下面是正则表达式的分解:

Here's a breakdown of the regex:

  • \ S &ndash的;任何空白字符
  • + &ndash的;匹配一个或多个所述previous令牌;即,匹配一个或多个空格字符
  • $ &ndash的;所述字符串的末尾
  • \s – any whitespace character
  • + – match one or more of the previous token; i.e., match one or more whitespace character
  • $ – the end of the string

因此​​,定期前pression将匹配尽可能多的空白,因为它可以是直接后跟字符串的末尾。换言之,后空白

Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.

该投资进入学习正规的前pressions将变得更有价值,如果你需要扩展后您的要求。

The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.

这篇关于如何删除一个字符串在Java中,只有尾部的空格,并保持领先的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆