简体   繁体   English

如何在Java中的字符串中添加数字和单词之间的空格?

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

i have a lot of string which contains also number like : LOD140IXAL COMP 1X240GG 我有很多字符串,其中也包含如下数字: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. 数字可以是字符串中的每个位置。

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 . 当应用于您的示例( LOD140IXAL COMP 1X240GG )时,它会生成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) . 为实现这一目标,它使用零宽度断言(前瞻和后观)

我想你想要的东西

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

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

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