Python regex – match and replace unknown length of elements

I have the following problem. Often data exists in a form:

IF X = (A OR B OR C OR ...)

where ... is a continuation of an often larger list. I would like to change it to:

IF X = 'A' OR X = 'B' OR X = 'C' OR ...

Where again, three dots are continuation. I have completely no idea how to solve it by regular expression or even how to ask properly about the solution.

How to do it?

Trainee Asked on November 5, 2019 in Python.
Add Comment
1 Answer(s)

You could use (\w+)(?= OR|\)$) after removing X = at the beginning:

Explanation:

(\w+) – match one or more of word-characters and store it inside capturing group,

(?= OR|\)$) – positive lookahead with alternation: assert what follows is OR or ) and end of the string

Replace it with X = \1, meaning replacing with X = followed by first capturing group.

Reviewer Answered on November 5, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.