a newbie regex question

S

Shoryuken

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
 
J

Jonathan Gardner

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()
 
M

Max Erickson

Dotan Cohen said:
Maybe you mean:
for match in re.finditer(r'\([A-Z].+[a-z])\', contents):
Note the last backslash was in the wrong place.

The location of the backslash in the orignal reply is correct, it is
there to escape the closing paren, which is a special character:
import re
s='Abcd\nabc (Ab), (ab)'
re.findall(r'\([A-Z].+[a-z]\)', s)
['(Ab), (ab)']

Putting the backslash at the end of the string like you indicated
results in a syntax error, as it escapes the closing single quote of
the raw string literal:
re.findall(r'\([A-Z].+[a-z])\', s)

SyntaxError: EOL while scanning single-quoted string

max
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Help for a newbie 13
My regex kung-fu is not strong =( 0
Why is regex so slow? 21
Newbie... 2
Tasks 1
Questions about regex 3
A newbie question 2
compound regex 0

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top