简体   繁体   English

如何将这两个Regex语句与String.repalceAll()合并为一个

[英]How can I combine these two Regex statements into one with String.repalceAll()

I have this string, 我有这串

"36635,36635,36635,36635 36635 36635 36635 36635-36635-36635"

By the end of it I would like 最后,我想

36635 36635 36635 36635 36635 36635 36635 36635 36635 36635

I've managed to achieve this with the below code. 我设法通过以下代码实现了这一点。

String original = "36635,36635,36635,36635   36635   36635 36635  36635-36635-36635";
String justSpaces =  original.replaceAll("[^0-9]", " ");
String oneSpaceMax = justSpaces.replaceAll(" {2,}", " ");
System.out.printf("Original: %s \n JustSpaces: %s \n oneSpaceMax: %s", original, justSpaces, oneSpaceMax);

Output 输出量

Original: 36635,36635,36635,36635   36635   36635 36635  36635-36635-36635 
JustSpaces: 36635 36635 36635 36635   36635   36635 36635  36635 36635 36635 
oneSpaceMax: 36635 36635 36635 36635 36635 36635 36635 36635 36635 36635

How can I combine those two regex statements? 如何合并这两个正则表达式语句? I've attempted using the Or | 我尝试使用Or | operator but with no luck. 运算符,但没有运气。

Use: 采用:

original = original.replaceAll("\\D+", " ");

\\\\D+ will match 1 or more non-digit (including spaces) and replacement is just a single space. \\\\D+将匹配1个或多个非数字(包括空格),并且替换仅是一个空格。

RegEx Demo 正则演示

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

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