简体   繁体   English

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

[英]How to add spaces between numbers in string with word and integer?

Having string like this 有这样的字符串

"APM35 2FAST4YOU -5ABBA STEVE0.5&Tom" “ APM35 2FAST4YOU -5ABBA STEVE0.5&Tom”

and using regular expression Im not getting result as I want to. 并使用正则表达式Im无法获得想要的结果。 How can I add space before and after of each integer? 如何在每个整数之前和之后添加空间? Code: 码:

String s = "APM35 2FAST4YOU -5ABBA STEVE0.5&Tom";
s = s.replaceAll("(\\d)([A-Za-z])", "\\1 \\2");
System.out.println(s);

I'm getting such result: 我得到这样的结果:

APM35 1 2AST1 2OU -1 2BBA STEVE0.5&Tom

and I'd like get this string as result: 我想得到这个字符串作为结果:

APM 35 2 FAST 4 YOU -5 ABBA STEVE 0.5 &Tom

You could do it in two steps: 您可以分两步进行操作:

String s = "APM35 2FAST4YOU -5ABBA STEVE0.5&Tom";
//add a space after the numbers
String step1 = s.replaceAll("(-?\\d\\.?\\d*)([^\\d\\s])", "$1 $2");
//add a space before the numbers
String step2 = step1.replaceAll("([^0-9\\-\\s])(-?\\d\\.?\\d*)", "$1 $2");

Try this: 尝试这个:

s.replaceAll("([^\\d-]?)(-?[\\d\\.]+)([^\\d]?)", "$1 $2 $3").replaceAll(" +", " ");

First regexp can generate some extra spaces, they are removed by second one. 第一个正则表达式可以生成一些额外的空间,第二个则将其删除。

Sorry I wrote too fast, but I might as well ask: are you sure Java's regex API is able to identify a group (\\1 and \\2)? 抱歉,我写得太快了,但我也可能会问:您确定Java的regex API能够识别组(\\ 1和\\ 2)吗?

Because it seems that parts of the string are replaced by actual 1s and 2s so this might not be the correct syntax. 因为似乎字符串的一部分被实际的1和2代替,所以这可能不是正确的语法。

(And it seems that you are only checking for numbers followed by text, not the other way arround.) (似乎您只在检查数字,然后是文本,而不是反过来。)

You could use the expression "(-?[0-9]+(\\.[0-9]+)?)" 您可以使用表达式“(-?[0-9] +(\\。[0-9] +)?)”

(0.5 is no integer, if you only want integers (-?[0-9]+) should be enough) (0.5不是整数,如果只需要整数(-?[0-9] +)就足够了)

and replace it with " \\1 " or " $1 " (Dont know which is the right one for Java) (Spaces before and after) 并将其替换为“ \\ 1”或“ $ 1”(不知道哪个是Java的正确选择)(前后的空格)

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

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