如何在Java中的字符串中的数字和单词之间添加空格? [英] How to add spaces between number and word in a string in Java?

查看:603
本文介绍了如何在Java中的字符串中的数字和单词之间添加空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多字符串,其中也包含数字,例如:LOD140IXAL COMP 1X240GG

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.

推荐答案

一种做到这一点的方法是使用正则表达式。用单个空格替换以下怪物应该可以解决问题:

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])"

应用于示例( LOD140IXAL COMP 1X240GG )时,它会生成 LODIXAL COMP 1 X 240 MG

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

这篇关于如何在Java中的字符串中的数字和单词之间添加空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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