【问题标题】:Java Regex : Replace characters between two specific characters with equal number of another characterJava Regex:用相等数量的另一个字符替换两个特定字符之间的字符
【发布时间】:2021-09-25 07:25:42
【问题描述】:

将起始字符“+”和结束字符“+”之间的所有字符替换为相同数量的“-”字符。
我的具体情况如下:

输入:+-+-+-+
输出:+-----+

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

这不起作用。如何在 Java 中实现输出?提前致谢。

【问题讨论】:

  • 你应该包括它是如何不工作的。你会得到什么。
  • 如果我的回答没有解决您的问题,请考虑更新问题。

标签: java regex


【解决方案1】:

您可以使用环视断言来使用此替换:

String repl = s.replaceAll("(?<=-)\\+(?=-)", "-");
//=> +-----+

RegEx Demo

(?&lt;=-)\\+(?=-) 将匹配一个+,如果它被- 包围。由于我们使用lookbehind 和lookahead,因此我们不使用字符,这些只是断言。

【讨论】:

    【解决方案2】:

    你的匹配是重叠的,看:

    +-+-+-+
     ^^^
        Match found and replaced by "---"
    
    +---+-+
        ^
        +-- Next match search continues from here
    
    WARNING: No more matches found!
    

    为确保下一场比赛中没有连字符,您需要用positive lookahead 包裹尾随- 并使用-- 作为替换模式:

    String s = = "+-+-+-+";
    s = s.replaceAll("-\\+(?=-)","--")
    

    请参阅regex demo

    【讨论】:

    • 仅供参考:Here is a link 正则表达式调试器。如果有人想查看现在如何在当前字符串中找到匹配项,请单击▶️ 按钮。
    • 我尝试将它放入一个 sn-p,which works。但它需要用户同时展开和运行。
    猜你喜欢
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多