a newbie regex question
Jonathan Gardner
jgardner at jonathangardner.net
Thu Jan 24 16:41:04 EST 2008
On Jan 24, 12:14 pm, Shoryuken <sakradevanamin... at gmail.com> wrote:
> Given a regular expression pattern, for example, \([A-Z].+[a-z]\),
>
> print out all strings that match the pattern in a file
>
> Anyone tell me a way to do it? I know it's easy, but i'm completely
> new to python
>
> thanks alot
You may want to read the pages on regular expressions in the online
documentation: http://www.python.org/doc/2.5/lib/module-re.html
The simple approach works:
import re
# Open the file
f = file('/your/filename.txt')
# Read the file into a single string.
contents = f.read()
# Find all matches in the string of the regular expression and
iterate through them.
for match in re.finditer(r'\([A-Z].+[a-z]\)', contents):
# Print what was matched
print match.group()
More information about the Python-list
mailing list