0

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
Fla-Hyd
  • 279
  • 7
  • 17
  • Not sure what you mean. Do you want to replace a list of search terms? –  Feb 14 '13 at 07:04
  • Are you looking for a way to pre-compile your patterns? (re.compile)? – Yevgen Yampolskiy Feb 14 '13 at 07:06
  • 2
    In general, you [don't want to use regular expressions to parse HTML](http://stackoverflow.com/a/6751339/1142167). Look into an actual HTML parser such as [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). – Joel Cornett Feb 14 '13 at 07:10
  • @Mike yes i am planning to replace a list of search items. – Fla-Hyd Feb 14 '13 at 08:50

1 Answers1

2

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)
lgautier
  • 11,363
  • 29
  • 42
  • Firstly Thanks for the reply.Think I am planning to replace a set of search patterns with same value (In the above example i have replaced all the search patterns with "FINAL" value). I tried using the above code but i am not getting through. – Fla-Hyd Feb 14 '13 at 09:49