Match string not preceded by another with a regular expression

前端 未结 3 872
半阙折子戏
半阙折子戏 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

    0 讨论(0)
  • 2021-01-25 19:28

    In a .NET regex flavor, you may use lookbehinds like this:

    Match foo not immediately preceded with bar

    (?<!bar)foo
    

    See the regex demo.

    Match foo not preceded with bar anywhere in the string

    (?s)(?<!bar.*?)foo
    

    See the regex demo.

    Match foo immediately preceded with bar

    (?<=bar)foo
    

    See the regex demo.

    Match foo preceded with bar anywhere in the string

    (?s)(?<=bar.*?)foo
    

    See the regex demo.

    The latter contains .*? in the negative lookbehind allowing the regex engine to check for bar and any zero or more chars immediately to the left of foo, so the bar does not have to come immediately before foo.

    The (?s) inline modifier allows . to match any characters including newlines.

    The current problem is easily solved by using a negative lookbehind (see the top scenario),

    var result = Regex.Replace("XBB", "(?<!A)B", "AB");
    
    0 讨论(0)
  • 2021-01-25 19:29

    All B's not preceded by a A by AB.

    Find: (?<!A)B
    Replace: AB

    0 讨论(0)
提交回复
热议问题