multipattern substitution along with whitespace in python

Viewed 69

Input:

"good && toast&&guest &fast& slow||wind ||old|| new || very good"

Requirement: replace " && " with "and" (similarly " || " with "or") so my output for above should be as below:

"good and toast&&guest &fast& slow||wind ||old|| new or very good"

What I tried to do:

import re

new_ = {
                                '&&':'and',
                                '||':'or'
}

inpStr = "good && toast&&guest &fast& slow||wind ||old|| new || very good"
replDictRe = re.compile( r'(\s%s\s)' % '\s|\s'.join(map(re.escape, new_.keys())))
oidDesStr = replDictRe.sub(lambda mo:new_.get(mo.group(),mo.group()), inpStr)
print(oidDesStr)
1 Answers

You may use

replDictRe = re.compile( r'(?<!\S)(?:{})(?!\S)'.format('|'.join(map(re.escape, new_.keys()))) )

See the online Python demo and the regex demo.

The (?<!\S)(?:\&\&|\|\|)(?!\S) pattern means

  • (?<!\S) - matches a location not immediately preceded with a non-whitespace char (aka left-hand whitespace boundary)
  • (?:\&\&|\|\|) - either a && or || character substring
  • (?!\S) - a location not immediately followed with a non-whitespace char (aka right-hand whitespace boundary).
Related