Home > Back-end >  Extract values in name=value lines with regex
Extract values in name=value lines with regex

Time:09-05

I'm really sorry for asking because there are some questions like this around. But can't get the answer fixed to make problem.

This are the input lines (e.g. from a config file)

profile2.name=share2
profile8.name=share8
profile4.name=shareSSH
profile9.name=share9

I just want to extract the values behind the = sign with Python 3.9. regex.

I tried this on regex101.

^profile[0-9]\.name=(.*?)

But this gives me the variable name including the = sign as result; e.g. profile2.name=. But I want exactly the inverted opposite.

The expected results (what Pythons re.find_all() return) are

['share2', 'share8', 'shareSSH', 'share9']

CodePudding user response:

Try pattern profile\d \.name=(.*), look at Regex 101 example

import re
re.findall('profile\d \.name=(.*)', txt)
# output 
['share2', 'share8', 'shareSSH', 'share9']

But this problem doesn't necessarily need regex, split should work absolutely fine:

CodePudding user response:

Try removing the ? quantifier. It will make your capture group match an empty st regex101

CodePudding user response:

split will do it too.

t = '''
profile2.name=share2
profile8.name=share8
profile4.name=shareSSH
profile9.name=share9
'''
[e.split('=').pop() for e in t.splitlines() if e]
    
['share2', 'share8', 'shareSSH', 'share9']
  • Related