Reputation: 279
In the below case i have used "|"
condition in matching multiple search patterns and replacing all the search patterns with the value. It worked fine. But Does python has any MACRO type of thing where i can write all the patterns in it and call that in the search pattern? and replace all the patterns at once. Because i have to write almost 20 to 30 search patterns. Please help me in implementing this.
Thanks in Advance.
import re
st = '''<h5>Reglar</h5>
<h5>Lateral</h5>
<h5>Daily</h5>
<h5>Weekly</h5>
<h5>Monthly</h5>
<h5>Quaterly</h5>
<h5>Yearly</h5>
<h5>Halfyearly</h5>'''
vr = re.sub(r'(?i)<h5>(Lateral|Halfyearly|Monthly)</h5>', "<h5>FINAL</h5>", st)
print vr
Upvotes: 0
Views: 599
Reputation: 11545
Python does not have macros.
I am not certain to understand for sure what you are after but:
Strings containing the regular expression can be build programmatically:
frequncy_str = ('Lateral', 'Daily', 'Weekly', 'Monthly')
re_str = '(?i)<h5>(' + '|'.join(frequency_str) + ')</h5>'
For better performances, if the match is going to be performed several times one should compile the regular expression:
re_pat = re.compile(re_str)
Upvotes: 2