Search code examples
pythonregexlookbehind

Grouping lookbehind pattern along with matching regex search pattern to substitute as a whole


I have to search and replace a pattern with the following condition: if a string "y=2" is found in a line and if it is either preceded or not preceded by "x=" then substitute, the matched string "y=2" with "x=1 y=2". I am trying with the following

line="hello x=7 y=2"
m = re.search(r"((?<=x=\d\s)|(?<!x=\d\s))y=2", line)
if m:
    s = "x=1 " + m.group(0)
    line = re.sub(m.group(0), s, line)
    print line

I am getting output as hello x=7 x=1 y=2 which is different from my expected output: hello x=1 y=2

How to get the whole pattern including the lookbehind expression as a matched string? This will solve my problem.

m.group(0) always print y=1, and m.group(1) prints nothing

I want this to have the whole string "x=7 y=1" to make the substitution work properly


Solution

  • I don't think you need lookbehind pattern to do this. All the work is to substitute y=2 or x=\d y=2 to x=1 y=2, right?

    line="hello x=7 y=2"
    re.sub(r'(x=\d\s)?y=2', 'x=1 y=2', line)