How to add spaces between number and word in a string in Java?

时间秒杀一切 提交于 2019-11-30 09:05:41

问题


i have a lot of string which contains also number like : LOD140IXAL COMP 1X240GG

I would like to put whitespace between numbers and word if there isn't. the number could be every where in the string.


回答1:


One way to do this is using regular expressions. Replacing the following monster with a single space should do the trick:

"(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])"

When applied to your example (LOD140IXAL COMP 1X240GG), it produces LODIXAL COMP 1 X 240 MG.

In a nutshell, the regex looks for a letter immediately followed by a digit, or a digit immediately followed by a letter, and inserts a space between them. To achieve this, it uses zero-width assertions (lookahead and lookbehind).




回答2:


I think you want something like

myString.replaceAll( "(\\d)([A-Za-z])", "$1 $2" );


来源:https://stackoverflow.com/questions/8833751/how-to-add-spaces-between-number-and-word-in-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!