Quantcast
Channel: Python extract pattern matches - Stack Overflow
Viewing all articles
Browse latest Browse all 12

Answer by mgilson for Python extract pattern matches

$
0
0

You can use matching groups:

p = re.compile('name (.*) is valid')

e.g.

>>> import re>>> p = re.compile('name (.*) is valid')>>> s = """... someline abc... someother line... name my_user_name is valid... some more lines""">>> p.findall(s)['my_user_name']

Here I use re.findall rather than re.search to get all instances of my_user_name. Using re.search, you'd need to get the data from the group on the match object:

>>> p.search(s)   #gives a match object or None if no match is found<_sre.SRE_Match object at 0xf5c60>>>> p.search(s).group() #entire string that matched'name my_user_name is valid'>>> p.search(s).group(1) #first group that match in the string that matched'my_user_name'

As mentioned in the comments, you might want to make your regex non-greedy:

p = re.compile('name (.*?) is valid')

to only pick up the stuff between 'name ' and the next ' is valid' (rather than allowing your regex to pick up other ' is valid' in your group.


Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>