Reputation: 960
Lets say I have this variable
myvar = "81"
And I want to search through the lines that has strings like this and get the word inside the quotations:
static public Register myReg1 = new Register("D4_STAT_1", 81);
static public Register myReg2 = new Register("D5_STAT_1", 819);
In this case if I want to find the "D4_STAT_1", by searching for myvar in the file, I know how to read each line, but the problem for me is how to search for a variable and get exactly the word inside the quotations.
Thanks.
Upvotes: 1
Views: 116
Reputation: 2171
You can do it like this:
import re
myvar = 81
with open("myfile") as _file:
for line in _file:
match = re.search(('\((?P<register_name>".+"), %s\)' % re.escape(str(myvar))),
line)
if match:
print match.group("register_name")
Upvotes: 1
Reputation: 95318
>>> import re
>>> s = '''
... static public Register myReg1 = new Register("D4_STAT_1", 81);
... static public Register myReg2 = new Register("D5_STAT_1", 819);
... '''
>>> myvar = "81"
>>> re.search('static public Register \w+ = new Register\("(\w+)", %s\);' % re.escape(str(myvar)), s).group(1)
'D4_STAT_1'
Depending on the circumstances (the input file), you can also use a simpler:
>>> re.search('Register\("(\w+)", %s\);' % re.escape(str(myvar)), s).group(1)
'D4_STAT_1'
Upvotes: 2