How to extract data from file by using reg expr in python?

A forum for general discussion of the Python programming language.

How to extract data from file by using reg expr in python?

Postby vampo650 » Thu Mar 28, 2013 3:59 am

I have a file, in that emailid, phoneno and my dateofbirth is there. In python by using regular expression, how to find the 3 fields one by one? The desired output looks like
Code: Select all
 Emailid: x@gmail.com
 Phoneno: 1234567890
 dateofbirth: xx-xx-xx


I knew how to find the fields individually. But I am not aware how to find 3 at a time .The below snippet shows how to find the emailid from the file. This code output looks like
Code: Select all
Emaildid: x@gmail.com

Code: Select all
import sys,re

pattern=r'''(?P<emailid>[a-zA-Z\.]*\@[a-zA-Z]*\.c[a-zA-Z]*)'''


regobj = re.compile(pattern, re.VERBOSE)

for line in sys.stdin:
  results= regobj.finditer(line)
for result in results:
  sys.stdout.write("%s\n"%result.group('check'))
vampo650
 
Posts: 9
Joined: Wed Mar 20, 2013 6:32 am

Re: How to extract data from file by using reg expr in pytho

Postby snippsat » Thu Mar 28, 2013 1:09 pm

You can use group(),you group stuff together with ().
| can be used to match on both side match me|and me to

A quick example with your data,if your file is bigger this may break.
Code: Select all
import re

data = '''\
Emailid: x@gmail.com
Phoneno: 1234567890
dateofbirth: xx-xx-xx'''


for match in re.finditer(r'''(Emailid:\s\w+@\w+.\w+)
(Phoneno:\s\d+)
(dateofbirth:\s\w+-\w+-\w+)''', data, re.MULTILINE):
    #print match.group(1), match.group(2), match.group(3)
    print '\n'.join(match.group(i) for i in range(1,4))

'''Output-->
Emailid: x@gmail.com
Phoneno: 1234567890
dateofbirth: xx-xx-xx
'''
User avatar
snippsat
 
Posts: 156
Joined: Thu Feb 21, 2013 12:04 am


Return to General Discussions

Who is online

Users browsing this forum: Google [Bot] and 1 guest