regex - How to print tablename and primary key from file.sql in python -
i have requirement print tablename , primary key using below program. not working. please in solving this. have used regex pattern find out table name , primary key data in database schema.
class parsecreatefile: begin = re.compile(r"create \s+ table \s+'((?:[^']|'')*)'.+(primary \s+ key\s? \([^)]*\))", re.ignorecase | re.verbose | re.dotall) def __init__(self,filename): self.filename = filename self.readfromfile() def readfromfile(self): try: file = open(self.filename,'r') filedata = file.read() file.close() self.parse(filedata) except ioerror: print 'unable read file %s' % self.filename def parse(self,rawdata): self.list = [] while rawdata: mo = self.begin.search(rawdata) tablename, fil = mo.groups() print tablename, fil if mo none: break rawdata = rawdata[mo.end():] if __name__ == '__main__': print "only main classes" file = parsecreatefile('file2.sql')
file2.sql
create table 'x'( 'x' integer primary key(dn) 'y' short); create table 'y'( 'x1' integer primary key(dn1, dn2) 'y1' short); expected out: x: primary key(dn) y: primary key(dn1, dn2)
i edited regex, , used findall.
class parsecreatefile: begin = re.compile(r"create table[ ']*([^ ']+)[ ']*[(][^/;]+(primary key.*)[^/;]+;", re.ignorecase) def __init__(self,filename): self.filename = filename self.readfromfile() def readfromfile(self): try: file = open(self.filename,'r') filedata = file.read() file.close() self.parse(filedata) except ioerror: print 'unable read file %s' % self.filename def parse(self,rawdata): self.list = [] found = self.begin.findall(rawdata) in found: print i[0], i[1] if __name__ == '__main__': print "only main classes" file = parsecreatefile('file2.sql')
Comments
Post a Comment