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
 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

Code: Select all
import sys,re


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

for line in sys.stdin:
  results= regobj.finditer(line)
for result in results:
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 = '''\
Phoneno: 1234567890
dateofbirth: xx-xx-xx'''

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

Phoneno: 1234567890
dateofbirth: xx-xx-xx
We will be moving to on October 1 2016
User avatar
Posts: 1251
Joined: Thu Feb 21, 2013 12:04 am

Return to General Discussions

Who is online

Users browsing this forum: No registered users and 1 guest