Regular expressions: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
Line 6: Line 6:
</source>
</source>


== Finding a pattern in a loop ==
== Finding a patter with .findall ==
Findall returns different things depending on how many parentheses () you have in your pattern.


If there are no parentheses, it returns the complete text of the match one by one in the order it's found in the text:
<source lang="python">
<source lang="python">
for match in re.findall(r"the \w+", text):
for match in re.findall(r"the \w+", text):
Line 24: Line 26:
     the favourite
     the favourite


If there's one pair of parentheses, only the text inside the parentheses is returned:
<source lang="python">
<source lang="python">
for match in re.findall(r"the (\w+)", text):
for match in re.findall(r"the (\w+)", text):
Line 40: Line 43:
     favourite
     favourite


 
Finally, if there are multiple pairs of parentheses, findall returns a tuple of each:
<source lang="python">
<source lang="python">
for match in re.findall(r"(\w+) the (\w+)", text):
for match in re.findall(r"(\w+) the (\w+)", text):

Revision as of 22:30, 5 December 2013

Load some text from a file

Imagine you have some text, say from a text file:

text = open("pg105.txt").read()

Finding a patter with .findall

Findall returns different things depending on how many parentheses () you have in your pattern.

If there are no parentheses, it returns the complete text of the match one by one in the order it's found in the text:

for match in re.findall(r"the \w+", text):
    print match
   the use
   the terms
   the Project
   the Baronetage
   the limited
   the earliest
   the almost
   the last
   the page
   the favourite

If there's one pair of parentheses, only the text inside the parentheses is returned:

for match in re.findall(r"the (\w+)", text):
    print match
   use
   terms
   Project
   Baronetage
   limited
   earliest
   almost
   last
   page
   favourite

Finally, if there are multiple pairs of parentheses, findall returns a tuple of each:

for match in re.findall(r"(\w+) the (\w+)", text):
    print match
   ('for', 'use')
   ('under', 'terms')
   ('of', 'Project')
   ('but', 'Baronetage')
   ('contemplating', 'limited')
   ('of', 'earliest')
   ('over', 'almost')
   ('of', 'last')
   ('was', 'page')
   ('which', 'favourite')

Search & Replace with .sub

print re.sub(r"the (\w+)", r"the ONLY \1", text)
   The Project Gutenberg EBook of Persuasion, by Jane Austen
   This eBook is for the ONLY use of anyone anywhere at no cost and with
   almost no restrictions whatsoever.  You may copy it, give it away or
   re-use it under the ONLY terms of the ONLY Project Gutenberg License included
   with this eBook or online at www.gutenberg.net