Python-Ref > Regular expressions (regexp) > Regexp strategies II.
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Regexp strategies II.

How to use regexps effectively - be flexible
When you design your regexps carefully, it may happen that you will be too specific and in fact loose some hits. You should also look for such cases when debugging your regular expressions.
Expand/Shrink
Zdroj: (regexp12-1.py)
  1   import re
  2   
  3   text = '''<h1>This is the main title</h1>
  4   <p>some text.</p><p>some more</p>
  5   <p id="x112">some text here</p>
  6   <p>some more text</p>
  7   <h2>Secondary title</h2>
  8   <p class="red">text to show in red</p>'''
  9   
 10   # find all paragraphs - naive
 11   for p in re.findall('<p>.*?</p>', text):
 12     print p
 13   
 14   print "--------------------"
 15   # find all paragraphs - allow attributes
 16   for p in re.findall('<p.*>.*?</p>', text):
 17     print p
 18   
 19   print "--------------------"
 20   # find all paragraphs - allow attributes, non-greedy
 21   for p in re.findall('<p.*?>.*?</p>', text):
 22     print p
stdout:
<p>some text.</p>
<p>some more</p>
<p>some more text</p>
--------------------
<p>some text.</p><p>some more</p>
<p id="x112">some text here</p>
<p>some more text</p>
<p class="red">text to show in red</p>
--------------------
<p>some text.</p>
<p>some more</p>
<p id="x112">some text here</p>
<p>some more text</p>
<p class="red">text to show in red</p>
Doba běhu: 35.0 ms