Python regex: substitute all occurrence of a certain string NOT after a specific character

前端 未结 2 1856
猫巷女王i
猫巷女王i 2021-01-27 07:51

How can I substitute all occurrence of a certain string NOT after a specific character in Python?

For example, I want to substitute all occurrence of abc NO

相关标签:
2条回答
  • 2021-01-27 08:43
    result = re.sub("(?<!x)abc", "def", subject)
    
    • The negative lookbehind (?<!x) asserts that what precedes is not x
    • abc matches abc
    • We replace with def

    Reference

    • Lookahead and Lookbehind Zero-Length Assertions
    • Mastering Lookahead and Lookbehind
    0 讨论(0)
  • 2021-01-27 08:47

    With a negative lookbehind assertion (?<!...) (i.e. not preceded by):

    (?<!x)abc
    

    In a replacement:

    re.sub(r'(?<!x)abc', r'def', string)
    
    0 讨论(0)
提交回复
热议问题