Home > database >  Regex with python dictionary
Regex with python dictionary

Time:08-05

I am trying to do some "batch" find and replace.

I have the following string:

abc123 = abc122   V[2]   V[3]

I would like to find every instance of abc{someNumber} = and replace the instance's abc portion with int ijk{someNumber} =, and also replace V[3] with a keyword in a dictionary.

dictToReplace={"[1]": "_i", "[2]":"_j", "[3]":"_k"}

The expected end result would be:

ijk123 = ijk122   V_j   V_k

What is the best way to achieve this? RegEx for the first part? Can it also be used for the second?

CodePudding user response:

I'd split the logic in two steps:

1.) First replace the keyword abc\d 2.) Replace the keys found in dictionary with their respective values

import re

dictToReplace = {"[1]": "_i", "[2]": "_j", "[3]": "_k"}

s = "abc123 = abc122   V[2]   V[3]"

pat1 = re.compile(r"abc(\d )")
pat2 = re.compile("|".join(map(re.escape, dictToReplace)))

s = pat1.sub(r"ijk\1", s)
s = pat2.sub(lambda g: dictToReplace[g.group(0)], s)

print(s)

Prints:

ijk123 = ijk122   V_j   V_k

CodePudding user response:

Use a function as the replacement value in re.sub(). It can then look up the matched value in the dictionary to get the replacement.

string = 'abc123 = abc122   V[2]   V[3]'
# change abc### to ijk###
result = re.sub(r'abc(\d )', r'ijk\1', string)
# replace any V[###] with V_xxx from the dict.
result = re.sub(r'V(\[\d \])', lambda m: 'V'   dictToReplace.get(m.group(1), m.group(1)), result)
  • Related