Question: where to find detailed description and working examples of Python regular expressions?
1
gravatar for natasha.sernova
2.6 years ago by
natasha.sernova3.5k
natasha.sernova3.5k wrote:

Dear all!

I know Python regexps were taken from Perl, but in my opinion they lost a lot in this transition.

So far I've found several "theoretical" examples of Python regular expression application.

There are a few ways to search for them, like 'match' or 'findall' depending on the final goal.

This is not enough for me, I need your advice where to find more information with short script examples?

Many-many thanks!

Natasha

Example of my unsuccessul trials with SwissProt file:

import re
import random
import math
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)

#if m:
#print 'Match found: ', m.group()
#else:
#print 'No match' 

fin = open(sys.argv[1], 'r')
for line in fin:
    a = re.match(r'^AC', line)
    if a is not None:
        a.group
    a = re.match(r'^DE', line)
    if a is not None:
        a.group
    a = re.match(r'^OC', line)
    if a is not None:
        a.group
    a = re.match(r'^KW', line) 
    if a is not None:
        a.group
    a = re.match(r'(^SQ).+(\d+\s+\w{2})', line)
    if a is not None:
        a.group 
#        print "\1"+"\s"+"\2"
    re.sub(r'[\s,\n]','', line) 
    print line
    a = re.match(r'^//', line) 
    if a is not None:   
        break
fin.close()

I've got the whole initial SwissProt-file,

regexp python • 755 views
ADD COMMENTlink modified 2.6 years ago • written 2.6 years ago by natasha.sernova3.5k
2

beside documentation of course, that could help you

http://www.diveintopython3.net/regular-expressions.html
https://pymotw.com/2/re/

and for example you can test by yourself here

ADD REPLYlink modified 2.6 years ago • written 2.6 years ago by Medhat8.4k

That's perfect! Thousand thanks! I've never seen anything similar - usually a few lines and that's it.

ADD REPLYlink written 2.6 years ago by natasha.sernova3.5k
3

Note: It is better performance to use

with open("yourfile", "r"):
        # do something

# instead of

myfile =  open("yourfile", "r")
ADD REPLYlink written 2.6 years ago by Medhat8.4k

Thank you very much again! I've realized that I write regexps from Perl in Python...

ADD REPLYlink written 2.6 years ago by natasha.sernova3.5k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 826 users visited in the last hour