-1

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
4
  • Not sure what you mean. Do you want to replace a list of search terms? Commented Feb 14, 2013 at 7:04
  • Are you looking for a way to pre-compile your patterns? (re.compile)? Commented Feb 14, 2013 at 7:06
  • 2
    In general, you don't want to use regular expressions to parse HTML. Look into an actual HTML parser such as BeautifulSoup. Commented Feb 14, 2013 at 7:10
  • @Mike yes i am planning to replace a list of search items. Commented Feb 14, 2013 at 8:50

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.