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

ε祈祈猫儿з 提交于 2019-11-29 12:24:16

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).

Dawood ibn Kareem

I think you want something like

myString.replaceAll( "(\\d)([A-Za-z])", "$1 $2" );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!