Capture groups in Python regex issue -


i'm searching string number of copies: in text file , once it's found, want print digits associated it, i'm searching for, (\snumber of copies: (\d{1,2})) , want return (\d{1,2}). i've been researching nested groups in regex, don't have syntax down in python. appreciated.

zdiscs = re.search(r'(\snumber of copies: (\d{1,2}))', fi2content, re.m|re.i) print(zdiscs.group(1)) 

here line i'm looking in text file looks like:

12/13/2013 08:11:25  number of discs in set: 2 - number of copies: 2 

my desired output 2 , 2 because i'm looking number follows text.

fi2content represent whole text file read python.

i can print(zdiscs) can't print(zdiscs.group(2)). why?

i following error:

attributeerror: 'nonetype' object has no attribute 'group' 

when try print(zdiscs.group(2))

here's whole script if helps troubleshooting

fo = open('outputfile', 'w') fo.write("col1|col2|col3\n") # 1.walk around directory , find lastjob.txt file in 1 of folders rootdir = "c:\\users\bob\desktop\path parsing project" path, dirs, files in os.walk(rootdir): filename in files:     fullpath = os.path.join(path, filename)     if filename=="text.txt":         print(fullpath)         # 2.open file. read file         fi2 = open(fullpath, 'r')         fi2content = fi2.read()         zdiscs = re.search(r'(\snumber of copies: (\d{1,2}))', fi2content, re.m|re.i)         print(zdiscs.group(2)) #this error occurs!!!!!!!!!!!!! 

you must looking for:

import re zdiscs = re.search(r'(\snumber of copies: (\d{1,2}))', " 12/13/2013 08:11:25  number of discs in set: 2 - number of copies: 2", re.i) print(zdiscs.group(2)) 

see ideone demo

output: 54

mind re.m redundant in regex not have anchors ^ , $ in pattern (only behavior impacted option).

if use (\snumber of copies: (\d{1,2})), there 2 capturing groups, , number in group 2.

if file search expression not contain text, , want skip it, check if obtained match object:

zdiscs = re.search(r'(\snumber of copies: (\d{1,2}))', fi2content, re.i) if zdiscs:     print(zdiscs.group(2)) 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -