Match string not preceded by another with a regular expression

前端 未结 3 908
半阙折子戏
半阙折子戏 2021-01-25 18:32

The statement

Regex.Replace(\"XB\", \"([^A])B\", \"$1AB\")

produces XAB, as expected. Can someone explain me why

R         


        
3条回答
  •  野性不改
    2021-01-25 19:27

    Note that this ([^A])B regex matches the first XB and captures the X . Because the B following the X is already present in a match, so it won't be matched another time. In this case, i suggest you to use lookarounds.

    ([^A])(?=B)
    

    (?=B) Positive lookahead which asserts that the match must be followed by the letter B.

    But it produces XABBABB when the replacement string is $1AB. To get the desired output, just remove the B from the replacement string. That is replace the matched characters with \1A

    DEMO

提交回复
热议问题