where to find detailed description and working examples of Python regular expressions?
0
1
Entering edit mode
7.4 years ago
natasha.sernova ★ 4.0k

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,

Python regexp • 1.6k views
ADD COMMENT
2
Entering edit mode

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 REPLY
0
Entering edit mode

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

ADD REPLY
3
Entering edit mode

Note: It is better performance to use

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

# instead of

myfile =  open("yourfile", "r")
ADD REPLY
0
Entering edit mode

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

ADD REPLY

Login before adding your answer.

Traffic: 1999 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6