Python extract pattern matches

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

    It seems like you're actually trying to extract a name vice simply find a match. If this is the case, having span indexes for your match is helpful and I'd recommend using re.finditer. As a shortcut, you know the name part of your regex is length 5 and the is valid is length 9, so you can slice the matching text to extract the name.

    Note - In your example, it looks like s is string with line breaks, so that's what's assumed below.

    ## covert s to list of strings separated by line:
    s2 = s.splitlines()
    
    ## find matches by line: 
    for i, j in enumerate(s2):
        matches = re.finditer("name (.*) is valid", j)
        ## ignore lines without a match
        if matches:
            ## loop through match group elements
            for k in matches:
                ## get text
                match_txt = k.group(0)
                ## get line span
                match_span = k.span(0)
                ## extract username
                my_user_name = match_txt[5:-9]
                ## compare with original text
                print(f'Extracted Username: {my_user_name} - found on line {i}')
                print('Match Text:', match_txt)
    

提交回复
热议问题