Extract values in name=value lines with regex
Question:
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']
Answers:
Try removing the ? quantifier. It will make your capture group match an empty st
regex101
Try pattern profiled+.name=(.*)
, look at Regex 101 example
import re
re.findall('profiled+.name=(.*)', txt)
# output
['share2', 'share8', 'shareSSH', 'share9']
But this problem doesn’t necessarily need regex, split should work absolutely fine:
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']
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']
Try removing the ? quantifier. It will make your capture group match an empty st
regex101
Try pattern profiled+.name=(.*)
, look at Regex 101 example
import re
re.findall('profiled+.name=(.*)', txt)
# output
['share2', 'share8', 'shareSSH', 'share9']
But this problem doesn’t necessarily need regex, split should work absolutely fine:
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']