Garfield
Garfield

Reputation: 2537

Python: replace named groups by dictionary

How can I replace \s+ to single spance, all ; to ,, all a.m to AM, all x to y I am new to named group replacement, how could I replace set of characters to the set of replacement characters using single RegEx and single sub() calling.

If I can keep all replacement strings in a dict and have a single RegEx string that could be the smart way.

Eg: M-Th    5:30 am-10 pm; F    5:30 a.m-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 x y z x
Output: M-Th 5:30 AM-10 PM, F 5:30 AM - 10:30 PM, Sa 10:30 - 10:30, Su 10:30-10 y y z y

Upvotes: 1

Views: 399

Answers (2)

Himanshu
Himanshu

Reputation: 2454

Consider :-

import re
def sub(matchobj):
    if matchobj.group(0) == ';':
        return ':'
    elif matchobj.group(0) == 'a.m.':
        return 'AM'
    elif re.match('\\s+$', matchobj.group(0)):
        return ' '

print re.sub(';|\\s+|a.m.', sub, '10; a.m.          ;')

Sample run :-

C:\>python st.py
10:AM

Or perhaps ( borrowing from Ammar whose solution I liked for being concise :) :-

import re
mydict = {"\s+":" ", ";":",", "a.m":"AM","x":"y"}

def sub(matchobj):
    for k, v in mydict.iteritems():
        if re.match('%s$' % k, matchobj.group(0)):
            return v

print re.sub('|'.join(mydict.keys()), sub, 'M-Th    5:30 am-10 pm; F    5:30 a.m-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 x y z x')

Which works as well :-

C:\>python st.py
M-Th 5:30 am-10 pm, F 5:30 AM-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 y y

Upvotes: 1

Adem Öztaş
Adem Öztaş

Reputation: 21466

try this,

 mydict = {"\s+":" ", ";":",", "a.m":"AM","x":"y"}
 mystr = "M-Th    5:30 am-10 pm; F    5:30 a.m-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 x y z x"

 for k, v in mydict.iteritems():
    mystr = mystr.replace(k, v)

 print mystr

OUTPUT

M-Th    5:30 am-10 pm, F    5:30 AM-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 y y z y

Upvotes: 2

Related Questions