我使用了很多正则表达式来做到这一点,但问题是我也想考虑:
abc- -abc //should output abc-abc
abc -- abc //should output abc - abc
abc- - abc //should output abc- abc
abc - -abc //should output abc -abc
我用过:
String x=x.replaceAll("[\\-*]{2,}","-");
最佳答案
您可以使用以下正则表达式:
-(\\s*-)+
-
:字面匹配-
。(...)+
:分组(1+次)\\s*-
:匹配-
(可选)前置空格 (\s
)
x = x.replaceAll("-(\\s*-)+", "-");
关于java - 正则表达式用一个破折号替换 2 个或多个破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32023117/