Home > OS >  Python replace with regex
Python replace with regex

Time:09-26

I have two strings which contains the following substrings: myStringA and myStringBB; and a dictionary d which maps A and BB to some other values, lets say d["A"] = "X" and d["BB"] = "YY". I want to replace both of these strings by the following strings:

ThisIsMyStringX and ThisIsMyStringYY;. So that I want to replace A and BB (which are known for me) by the values from dictionary and leave ; if present at the end and add ThisIs and the beginning. How can I achieve that?

CodePudding user response:

You can use regex match-groups to achieve these replacements (a Match group is a Part of an regex encapsulated by brackets). For example:

import re

regex=re.compile("foo(bar)")
match = regex.match("foobar")
print(match.group(1))

will print "bar".
Here ist a working programm that solves your specific Problem:

import re

dict = {
   "A": "X",
   "BB": "YY"
}
myStringA = "myStringA"
myStringBB = "myStringBB"

regex = re.compile("my(\w )(A|BB)")

match = regex.match(myStringA)
print("ThisIsMy"  match.group(1)   
dict[match.group(2)])

match = regex.match(myStringBB)
print("ThisIsMy"  match.group(1)   
dict[match.group(2)])
  • Related