简体   繁体   English

Java正则表达式仅删除数字之间的空格

[英]Java regex to remove space between numbers only

I have some strings like: 我有一些像这样的字符串:

String a = "Hello 12 2 3 4 45th World!";

I wanna concatenate numbers as: "Hello 12234 45th World" 我想将数字连接为: "Hello 12234 45th World"

By trying a.replaceAll("(?<=\\\\d) +(?=\\\\d)", "") , I got the result as: "Hello 1223445th World" . 通过尝试a.replaceAll("(?<=\\\\d) +(?=\\\\d)", "") ,我得到的结果是: "Hello 1223445th World"

Is there any way to concatenate only numbers, not number + th ? 有什么办法只能连接数字,而不是数字 + th

(?<=\\d) +(?=\\d+(?:\\s|$))

You can try this.See demo. 您可以尝试一下。请参阅演示。

https://regex101.com/r/nS2lT4/43 https://regex101.com/r/nS2lT4/43

You just need to add a word boundary in the look-ahead to only match numbers as whole words: 您只需要在预读中添加单词边界即可将数字匹配为整个单词:

a.replaceAll("(?<=\\d) +(?=\\d+\\b)", ""))

Sample code on IDEONE : IDEONE上的示例代码

String a = "Hello 12 2 3 4 45th World!";
System.out.println(a.replaceAll("(?<=\\d) +(?=\\d+\\b)", ""));

Output: 输出:

Hello 12234 45th World!

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

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