Q:

python regex with variable input

I've a text file (say test.txt) e.g.
a  ......
aa ......
a+a .....
aa+ .....
a+  .....
aaa .....
.........

Now I would like to find the line number of any particular strings e.g. 'a', 'aa+' etc. I've tried to find an exact match of the input string using regex.
name='a'

import re
p = re.compile(r'\b'+re.escape(name)+ r'\b')

i=0
with open('test.txt') as inpfile:
    for num, line in enumerate(inpfile):
        if p.search(line):
            print num

The program should print "0" only but its printing 0,2,4. 
My expected output is
name='a'

output: 0
name='aa'

output: 1
name='aa+'

output: 3 and so on...
I understood that the regular expression I used above, is not correct. But it will be helpful if you please share your comments/suggestions to compile the regular expression such a way that it gives the desired output for all the patterns.
Thanks.

A:

Why would it not print 2 and 4? a+a and a+ both contain a surrounded by word boundaries, exactly as you have specified with \b. Perhaps you want to match the start and end of the line instead?  E.g.
name='a'

import re
p = re.compile('^'+re.escape(name)+ '$')

with open('test.txt') as inpfile:
    for num, line in enumerate(inpfile):
        if p.search(line.rstrip(r'\n')):
            print num

But if you're looking to match the line exactly, why go to the trouble of using a regular expression?
name='a'

with open('test.txt') as inpfile:
    for num, line in enumerate(inpfile):
        if name == line.rstrip(r'\n'):
            print num

