Take part of a regex search result in Python -
Take part of a regex search result in Python -
i want read in header file , output each of variables has form x = 1.0; double = x;
at moment i've got this, outputs whole line:
import re input = open("file_with_vars.hpp", 'r') out = open("output.txt", 'w') line in input: if re.match("(.*) = (\d)", line): print >> out, line but can't work out how take part of line , output variable name , double string file.
edit: have
for line in cell: m = re.search('(.*)\s*=\s*(\d+\.\d+)', line) print m.group() but error ' attributeerror: 'nonetype' object has no attribute 'group' '
use search instead of match
the regex .*\s*=\s*\d+\.\d+
test:
import re y="x=1.0" m=re.search('(.*)\s*=\s*(\d+\.\d+)',y) the group function can used extract matched strings as
>>> print m.group() 'x=1.0' >>> print m.group(1)` 'x' >>> print m.group(2) '1.0' edit
how search lines within file
for line in cell: try: m = re.search('(.*)\s*=\s*(\d+\.\d+)', line) print m.group() except attributeerror: pass the nonetype error caused because lines in file doesnot match regex returning none search method.
the try except takes care of exception.
pass null statement in python
for input file
x=10.2 y=15.3 z=12.4 w=48 creates output as
x=10.2 y=15.3 z=12.4 see here w=48 doesnt match regex returning nonetype, safely handled try block
or
as jerry pointed out, if can create more simple
for line in cell: m = re.search('\s*\s*=\s*(\d+\.\d+)', line) if m: print m.group() python regex
Comments
Post a Comment