0

有这样的字符串

“APM35 2FAST4YOU -5ABBA STEVE0.5&汤姆”

并使用正则表达式我没有得到我想要的结果。如何在每个整数之前和之后添加空格?代码:

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

我得到这样的结果:

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

我想得到这个字符串作为结果:

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

4 回答 4

4

您可以分两步完成:

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");
于 2013-05-30T15:02:07.507 回答
2

尝试这个:

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

第一个正则表达式可以生成一些额外的空格,它们被第二个删除。

于 2013-05-30T15:06:59.237 回答
0

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

Because it seems that parts of the string are replaced by actual 1s and 2s so this might not be the correct syntax.

(And it seems that you are only checking for numbers followed by text, not the other way arround.)

于 2013-05-30T14:58:46.227 回答
0

您可以使用表达式“(-?[0-9]+(\.[0-9]+)?)”

(0.5 不是整数,如果你只想要整数 (-?[0-9]+) 就足够了)

并将其替换为“ \1 ”或“ $1 ”(不知道哪个是正确的Java)(之前和之后的空格)

于 2013-05-30T15:02:26.413 回答