regex - Searching and capturing a character using regular expressions Python -


while going through 1 of problems in python challenge, trying solve follows:

read input in text file characters follows:

dqheabsamljtmaokmnslzivmenfxqdatqijitwtychyemwqtnxbblxwzngmdqhhxnlhfeyvzxmhsxzd bebaxeapgqpttvqrvxhpeoutisttpdeeugfgmdkkqceyjusuigrogfypzkqgvccdbkrcywhflvpzdmek myupxvgtgsvwgrybkonbeghqhuxhhnyjfwsftfaiwtaombzescsosumwpssjcpllblspigffdlpzzmkz jarrjufhgxdrzywwosrblprasvrupzlaubtdhgzqtvzovhevstbhpitdlluljvvwrwvhpnvzewvyhmps kmvcdehzfzxtwocgvakhhcnozrsbwsiehpenfjarjlwwcvkftlhuvsjcziyfpcyrojxopkxhvucqcuge luwlbcmqpwdvupubrrjzhfexhxsbvljqjvvfegruwrshpekujcpmpisrv....... 

what need go through text file , pick lower case letters enclosed 3 upper-case letters on each side.

the python script wrote above follows:

import re  pattern = re.compile("[a-z][a-z]{3}([a-z])[a-z]{3}[a-z]") f = open('/users/dev/sometext.txt','r') line in f:     result = pattern.search(line)     if result:        print result.groups()   f.close() 

the above given script, instead of returning capture(list of lower case characters), returns text blocks meets regular expression criteria, like

axcsdfghj vcdfetyha nhjuikjho ......... ......... 

can tell me doing wrong here? , instead of looping through entire file, there alternate way run regular expression search on entire file?

thanks

change result.groups() result.group(1) , single letter match.

a second problem code not find multiple results on 1 line. instead of using re.search you'll need re.findall or re.finditer. findall return strings or tuples of strings, whereas finditer returns match objects.

here's approached same problem:

import urllib import re      pat = re.compile('[a-z][a-z]{3}([a-z])[a-z]{3}[a-z]') print ''.join(pat.findall(urllib.urlopen(     "http://www.pythonchallenge.com/pc/def/equality.html").read()))  

note re.findall , re.finditer return non-overlapping results. when using above pattern re.findall searching against string 'abbbcdddefffg', match 'c', not 'e'. fortunately, python challenge problem contains no such such examples.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -