Python extract pattern matches

前端 未结 9 1511
小蘑菇
小蘑菇 2020-11-22 06:36

Python 2.7.1 I am trying to use python regular expression to extract words inside of a pattern

I have some string that looks like this

someline abc
s         


        
9条回答
  •  灰色年华
    2020-11-22 07:07

    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'
    

提交回复
热议问题