Number of regex matches

前端 未结 6 1856
长情又很酷
长情又很酷 2020-12-05 03:49

I\'m using the finditer function in the re module to match some things and everything is working.

Now I need to find out how many matches

相关标签:
6条回答
  • 2020-12-05 04:18

    I know this is a little old, but this but here is a concise function for counting regex patterns.

    def regex_cnt(string, pattern):
        return len(re.findall(pattern, string))
    
    string = 'abc123'
    
    regex_cnt(string, '[0-9]')
    
    0 讨论(0)
  • 2020-12-05 04:21

    If you know you will want all the matches, you could use the re.findall function. It will return a list of all the matches. Then you can just do len(result) for the number of matches.

    0 讨论(0)
  • 2020-12-05 04:21

    If you find you need to stick with finditer(), you can simply use a counter while you iterate through the iterator.

    Example:

    >>> from re import *
    >>> pattern = compile(r'.ython')
    >>> string = 'i like python jython and dython (whatever that is)'
    >>> iterator = finditer(pattern, string)
    >>> count = 0
    >>> for match in iterator:
            count +=1
    >>> count
    3
    

    If you need the features of finditer() (not matching to overlapping instances), use this method.

    0 讨论(0)
  • 2020-12-05 04:23

    For those moments when you really want to avoid building lists:

    import re
    import operator
    from functools import reduce
    count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string))) 
    

    Sometimes you might need to operate on huge strings. This might help.

    0 讨论(0)
  • 2020-12-05 04:26

    If you always need to know the length, and you just need the content of the match rather than the other info, you might as well use re.findall. Otherwise, if you only need the length sometimes, you can use e.g.

    matches = re.finditer(...)
    ...
    matches = tuple(matches)
    

    to store the iteration of the matches in a reusable tuple. Then just do len(matches).

    Another option, if you just need to know the total count after doing whatever with the match objects, is to use

    matches = enumerate(re.finditer(...))
    

    which will return an (index, match) pair for each of the original matches. So then you can just store the first element of each tuple in some variable.

    But if you need the length first of all, and you need match objects as opposed to just the strings, you should just do

    matches = tuple(re.finditer(...))
    
    0 讨论(0)
  • 2020-12-05 04:28
    #An example for counting matched groups
    import re
    
    pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
    search_str = "My 11 Char String"
    
    res = re.match(pattern, search_str)
    print(len(res.groups())) # len = 4  
    print (res.group(1) ) #My
    print (res.group(2) ) #11
    print (res.group(3) ) #Char
    print (res.group(4) ) #String
    
    0 讨论(0)
提交回复
热议问题