java - Remove every space EXCEPT leading spaces
问题描述
I need to remove every spaces from a String EXCEPT leading spaces.
I have some strings that look like this :
" h ello"
And I am trying to achieve this :
" hello"
That's like a reverse trim()
.
What's the most efficient way to go about it ?
解决方案
You can use replaceAll with this regex (?<=\S)(\s+)(?=\S)
like this :
str = str.replaceAll("(?<=\\S)(\\s+)(?=\\S)", "");
Examples of input & outputs:
" h ello " => " hello "
" hello, word " => " hello,word "
The first regex keep only leading and trailing spaces, if you want to keep only the leading spaces, then you can use this regex (?<=\S)(\s+)
.
Examples of input & outputs:
" hello " => " hello"
" hello, word " => " hello,word"
推荐阅读
- javascript - 从 AngularJS 1.5 升级到 1.7 会抛出“无法复制!不支持复制 Window 或 Scope 实例”
- html - DevicePixelRatio 似乎突然与 Windows 比例叠加
- python - 获取二维数组中最近的坐标
- python - 为什么 vgg.prepare() 方法会创建给定图像的 9 个副本?
- python - 用于模式研究的 Python 正则表达式
- php - 如何显示输入数组的验证错误?
- ios - 在包含 collectionView 的 tableview XIB 中呈现 DocumentInteractionController
- java - 如何为 JButtons 设置动作侦听器以打开相应的面板
- c# - 如何在C#中选择保存excel文件的路径
- java - 获取存储在 WEB-INF 中的文件的相对路径?