gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:34:26 25 4
gpt4 key购买 nike

我使用了很多正则表达式来做到这一点,但问题是我也想考虑:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com