pythonregex

Matching end of string or ; in regex


Why does the following regex not match the last occurrence of the search word?

(?i)(^|,|;)\s*old\s*($|;)

This matches the first and second old, but not the third:

One,old;Two,old;old
     ^       ^   ^
   match   match  \_ no match

However, if I remove the last ; ((?i)(^|,|;)\s*old\s*$), it does match the last occurrence.

P.S. I'm using Python.


Solution

  • You could capture what comes before it (^|[,;]) match what you want to replace and assert (?=$|;) what should be to the right.

    For the comma and the semicolon you can use a character class.

    In the replacement use the capture group \1

    (^|[,;])\s*old\s*(?=$|;)
    

    Regex demo