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

标签 java regex string replaceall

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

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/

相关文章:

ruby - 在 Ruby 中从 stdin 读取并打印到 stdout

java - 如何为 Android Studio 定义 JAVA_HOME 变量?

java - 使用 Hadoop 时如何解决 NoClassDefFoundError?

java - 如何安排自动打印作业?

java - 接口(interface)中的变量

c# - String.Intern 和 String.IsInterned 有什么区别?

java - 条件替换的正则表达式

java - 正则表达式替换匹配后出现的所有匹配项

c# - 无法使用正则表达式删除不可见字符

linux - 如何将行添加到 sed 输出的开头