Python extract pattern matches

前端 未结 9 1497
小蘑菇
小蘑菇 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)
    
    0 讨论(0)
  • 2020-11-22 07:29

    Maybe that's a bit shorter and easier to understand:

    import re
    text = '... someline abc... someother line... name my_user_name is valid.. some more lines'
    >>> re.search('name (.*) is valid', text).group(1)
    'my_user_name'
    
    0 讨论(0)
  • 2020-11-22 07:30

    You want a capture group.

    p = re.compile("name (.*) is valid", re.flags) # parentheses for capture groups
    print p.match(s).groups() # This gives you a tuple of your matches.
    
    0 讨论(0)
提交回复
热议问题