正则表达式用一个破折号替换 2 个或更多破折号

Regex replace 2 or more dashes with one dash

我用过很多正则表达式来做这个,但问题是我还想考虑:

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*-:匹配 - 可选 space (\s) 前置

x = x.replaceAll("-(\s*-)+", "-");