Regular Expressions: Get number of matches

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Xx r3negade
    New Member
    • Apr 2008
    • 39

    Regular Expressions: Get number of matches

    How do you return the number of times a certain pattern has been matched in a string?
  • kaarthikeyapreyan
    New Member
    • Apr 2007
    • 106

    #2
    Hey try this it would match the pattern for the string given

    Code:
    #! /usr/bin/env python
    ### Program to match the given sequence in a word
    
    def pattern():
      """
      Search for a pattern in a string
      """
      count = 0
      rex=raw_input("Enter the pattern : ")
      mystr=raw_input("Enter the string : ")
      patlen = len(rex)
      word_split=group(patlen,mystr)
      
      for j in word_split :
        if j == rex :
          count = count + 1
          
      if rex in word_split :
        print "Pattern Found %d time(s)"%count 
      else :
        print "Pattern not found"
    
    def group(exprlength,word):
      """
      group characters for a given length
      """
      strlist = []
      i = 0
      for count in word :
        relpat = word[i:i+exprlength]
        if len(relpat) == exprlength:
          strlist.append(relpat)
          i = i +1
      return strlist
    
    pattern()

    Comment

    • Smygis
      New Member
      • Jun 2007
      • 126

      #3
      You use the len functon.

      [code=python]
      >>> import re
      >>> txt = open("mess.text ").read()
      >>> len(txt)
      101250
      >>> rexp = re.compile(r"re gexp here*")
      >>> match = rexp.findall(tx t)
      >>> len(match)
      10
      [/code]

      * Censored due to being the sulution for a puzzle in pythonchallange . :)

      w00t, no python highlighting for the code?

      Comment

      • jlm699
        Contributor
        • Jul 2007
        • 314

        #4
        Originally posted by Smygis
        w00t, no python highlighting for the code?
        This has been an issue for some time now. Nobody has acknowledged it aside from one of the Moderators. I miss the python highlights :(

        P.S. If a moderator is reading this do you have any idea why this is happening or could you contact an admin and try to figure out when it will be back?

        Comment

        • Laharl
          Recognized Expert Contributor
          • Sep 2007
          • 849

          #5
          They're discussing it here.

          Comment

          Working...