AmacOS
AmacOS

Reputation: 311

String substitution using regex in Python with overlapping pattern

I am trying to find && using regex and substitute it with and using Python. Here is my regex:

r"(?=( && ))"

test input: x&& &&& && && x || | ||\|| x, expected output: x&& &&& and and x or | ||\|| x. My Python code:

import re

input = "x&& &&& && && x || | ||\|| x"
result = re.sub(r"(?=( && ))", " and ", input)
print(result)

My output is: x&& &&& and && and && x || | ||\|| x. This actually works, but instead of substitution it leaves the original pattern just adds my substitution string when it finds pattern. This is really confusing.

Upvotes: 2

Views: 340

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

Your output is consistent with your statement of the problem (sic):

I am trying to find " && " and substitute it with " and "

Since the output is not what you want there must be a problem with your statement of the problem. I believe you actually want:

I am trying to find " &&" followed by a space and substitute it with " and"

Once you get that right it's just a matter of translating it to a regular expression:

import re

s = 'x&& &&& && && x || | ||\|| x'
print re.sub(r' &&(?= )', ' and', s)
  #=> x&& &&& and and x || | ||\|| x

Demo

(?= ) is a positive lookahead that asserts that the match is followed by a space.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

A capturing group inside a positive lookahead can be used to extract overlapping patterns. To replace them, you actually need to consume the text, lookarounds do not consume the text they match.

In this case, you only have an overlapping trailing space, so you might use either of the two approaches:

text = re.sub(r"( )&&(?= )", r"\1and", text)

Or, if you need to replace any && that is neither preceded nor followed with any whitespace char, use

text = re.sub(r"(?<!\S)&&(?!\S)", r"and", text)

Note that input is a Python builtin, you should name your text variable in a different way, say, text.

Upvotes: 2

Related Questions