Python extract pattern matches
python, regex
Solution
You need to capture from regex. `search` for the pattern, if found, retrieve the string using `group(index)`. Assuming valid checks are performed:
>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1) # group(1) will return the 1st capture (stuff within the brackets).
# group(0) will returned the entire matched text.
'my_user_name'
Problem
I am trying to use a regular expression to extract words inside of a pattern. I have some string that looks like this ``` someline abc someother line name my_user_name is valid some more lines ``` I want to extract the word `my_user_name`. I do something like ``` import re s = #that big string p = re.compile("name .* is valid", re.flags) p.match(s) # this gives me <_sre.SRE_Match object at 0x026B6838> ``` How do I extract `my_user_name` now?