Multiple, Specific, Regex Substitutions In Python
What I would like to do is to make specific substitions in a given text. For example, '<' should be changed to '[', '>' to ']', and so forth. It is similar to the solution gi
Solution 1:
import re
defmultiple_replace(dict, text):
# Create a regular expression from the dictionary keys
regex = re.compile(r'(%s)' % "|".join(dict.keys()))
return regex.sub(lambda mo: dict[
[ k for k indictif
re.search(k, mo.string[mo.start():mo.end()])
][0]], text)
d = { r'ba[rz]*' : 'bar', '<' : '[' }
s = 'barzzzzzz <'print multiple_replace(d, s)
Gives:
bar [
Solution 2:
Just do multiple sub
calls.
On an unrelated note, Jargon File to the rescue: Metasyntactic variables, foo.
Post a Comment for "Multiple, Specific, Regex Substitutions In Python"