Search code examples
pythonregexnegative-lookbehind

regex lookbehind if matches exclude entire lane


I am trying to match single character ] only if [! is not ahead.

Regex:
(?!(?:\[\!.*))\]
Expected Result:
_dynamic_text_[!_dynamic_text_]_dynamic_text_

_dynamic_text__dynamic_text_]_dynamic_text_
                            ↑

Current Result

_dynamic_text_[!_dynamic_text_]_dynamic_text_
                              ↑
_dynamic_text__dynamic_text_]_dynamic_text_
                            ↑

https://regex101.com/r/IIzoX5/1

I have consulted several reference sources, but I am still encountering difficulties in finding out how to accomplish this task.

Would you be able to offer me some guidance or advice?


Solution

  • You may use this regex:

    ^(?!.*\[!)[^]\n]*]
    

    RegEx Demo

    RegEx Details:

    • ^: Start
    • (?!.*\[!): Make sure we don't have [! anywhere till end
    • [^]\n]*: Match 0 or more of any character that is not ] and not a line break
    • ]: Match a ]