Python extract pattern matches

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

    You could use something like this:

    import re
    s = #that big string
    # the parenthesis create a group with what was matched
    # and '\w' matches only alphanumeric charactes
    p = re.compile("name +(\w+) +is valid", re.flags)
    # use search(), so the match doesn't have to happen 
    # at the beginning of "big string"
    m = p.search(s)
    # search() returns a Match object with information about what was matched
    if m:
        name = m.group(1)
    else:
        raise Exception('name not found')
    

提交回复
热议问题