N00b question: matching stuff with variables.

Thomas Jollans thomas at jollans.com
Mon Jun 28 13:46:47 EDT 2010


On 06/28/2010 07:29 PM, Ken D'Ambrosio wrote:
> Hi, all.  I've got a file which, in turn, contains a couple thousand
> filenames.  I'm writing a web front-end, and I want to return all the
> filenames that match a user-input value.  In Perl, this would be something
> like,
> 
> if (/$value/){print "$_ matches\n";}
> 
> But trying to put a variable into regex in Python is challenging me --
> and, indeed, I've seen a bit of scorn cast upon those who would do so in
> my Google searches ("You come from Perl, don't you?").
> 
> Here's what I've got (in ugly, prototype-type code):
> 
> file=open('/tmp/event_logs_listing.txt' 'r')   # List of filenames
> seek = form["serial"].value                    # Value from web form
> for line in file:
>    match = re.search((seek)",(.*),(.*)", line) # Stuck here


without re:

for line in file:
    if line.startswith(seek): # or: if seek in line...
        # do stuff

with re and classic string formatting:

for line in file:
    # or use re.match to look only at the beginning of the line
    match = re.search('(%s),(.*),(.*)' % seek, line)
    if match:
         #use match.group(n) for further processing

You could also concatenate strings to get the regexp, as in:
'('+seek+'),(.*),(.*)'

Note that while using re is perl way to do strings, Python has a bunch
of string methods that are often a better choice, such as str.startswith
or the ("xyz" in "vwxyz!") syntax.

if you just want to get the matching lines, you could use list
comprehension:

matching = [ln for ln in file if ln.startswith(seek)]

Just to present some of the ways you can do this in Python. I hope
you're enjoying the language.

-- Thomas




More information about the Python-list mailing list