regex - Searching exact variable in a text file using python -


this question has answer here:

i trying search exact variable in file not able so. i.e. if search 'akash' in file lines contain akash returned, if contain 'akashdeep' , not exact 'akash'.

__author__ = 'root' def useringroups(username):    open('/etc/group','r') data:        associatedgroups=[]        line in data:         if username in line:            associatedgroups.append(line.split(':')[0])    return associatedgroups  print useringroups('akash') 

this function must return lines containing 'akash' , not containing 'akashdeep'. tried using re module can not find example variable has been searched. tried:

for 'akash' in line.split(':')  

but in scenario if line contains multiple group entries fails.

hi have found solution problem of members responded post.here goes final solution

__author__ = 'root' import re  def findgroup(line,username):     result=re.findall('\\b'+username+'\\b',line)     if len(result)>0:         return true     else:         return false   def useringroups(username):    open('/etc/group','r') data:        associatedgroups=[]        line in data:         if findgroup(line,username):            associatedgroups.append(line.split(':')[0])    return associatedgroups    print useringroups('akas') 

Comments