Java String.replaceAll() with back reference

后端 未结 5 2043
天涯浪人
天涯浪人 2020-12-14 21:08

There is a Java Regex question: Given a string, if the \"*\" is at the start or the end of the string, keep it, otherwise, remove it. For example:

  1. *
5条回答
  •  醉梦人生
    2020-12-14 21:25

    You can use lookarounds in your regex:

    String repl = str.replaceAll("(?

    RegEx Demo

    RegEx Breakup:

    (?

    OP's regex is:

    (^\*)|(\*$)|\*
    

    It uses 2 captured groups, one for * at start and another for * at end and uses back-references in replacements. Which might work here but will be way more slower to finish for larger string as evident in # of steps taken in this demo. That is 209 vs 48 steps using look-arounds.

    Another smaller improvement in OP's regex is to use quantifier:

    (^\*)|(\*$)|\*+
    

提交回复
热议问题