How can I find all matches to a regular expression in Python?

后端 未结 1 1911

In a program I\'m writing I have Python use the re.search() function to find matches in a block of text and print the results. However, the program exits once i

相关标签:
1条回答
  • 2020-11-22 02:44

    Use re.findall or re.finditer instead.

    re.findall(pattern, string) returns a list of matching strings.

    re.finditer(pattern, string) returns an iterator over MatchObject objects.

    Example:

    re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
    # Output: ['cats', 'dogs']
    
    [x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
    # Output: ['all cats are', 'all dogs are']
    
    0 讨论(0)
提交回复
热议问题