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

Answer by Eugene Yarmash for Python extract pattern matches

$
0
0

You can use groups (indicated with '(' and ')') to capture parts of the string. The match object's group() method then gives you the group's contents:

>>> import re>>> s = 'name my_user_name is valid'>>> match = re.search('name (.*) is valid', s)>>> match.group(0)  # the entire match'name my_user_name is valid'>>> match.group(1)  # the first parenthesized subgroup'my_user_name'

In Python 3.6+ you can also index into a match object instead of using group():

>>> match[0]  # the entire match 'name my_user_name is valid'>>> match[1]  # the first parenthesized subgroup'my_user_name'

Viewing all articles
Browse latest Browse all 12

Trending Articles



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