Python extract pattern matches

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

    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'
    

提交回复
热议问题