Python extract pattern matches

前端 未结 9 1503
小蘑菇
小蘑菇 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:12

    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.

提交回复
热议问题