shantanuo
shantanuo

Reputation: 32316

Apply a dict to regex

I have a string and I need to hide the important details. For e.g.

x='Dear Mr /Ms Shantanu your agr no 1234 is expired on 13/11/2020 with arrears. Pls pay the arrear amount at your nearest branch'

The output should look something like this...

Dear Mr /Ms xxxx your agr no xxxx is expired on xx/xx/xxxx with arrears. Pls pay the arrear amount at your nearest branch

I have tried the following 3 statements and it works as expected.

re.sub(r'agr no \d+', 'agr no xxxx', x)
re.sub(r'expired on \d+\/\d+\/\d+','expired on xx/xx/xxxx', x)
re.sub(r'Mr /Ms \w+','Mr /Ms xxxx', x)

But there are a few more patterns. I have a dict that I need to apply to regular expression.

myreplace= {'agr no \d+': 'agr no xxxx', 'expired on \d+\/\d+\/\d+':'expired on xx/xx/xxxx', 'Mr /Ms \w+':'Mr /Ms xxxx'}

What is the best way to achieve this?

Upvotes: 0

Views: 40

Answers (1)

Robo Mop
Robo Mop

Reputation: 3553

Why not just make a simple list containing the regex and its substitution?

How about this:

import re

formatting = [[r'agr no \d+', 'agr no xxxx'], [r'expired on \d+\/\d+\/\d+', 'expired on xx/xx/xxxx'], [r'Mr /Ms \w+', 'Mr /Ms xxxx']]

s = 'Dear Mr /Ms Shantanu your agr no 1234 is expired on 13/11/2020 with arrears. Pls pay the arrear amount at your nearest branch'

for regex,substitution in formatting:
    s = re.sub(regex, substitution, s)

print(s)

The output is as expected.

formatting contains multiple lists like so: [[regex1, substitution1], [regex2, substitution2], ...]

Upvotes: 1

Related Questions