How do you return the number of times a certain pattern has been matched in a string?
Regular Expressions: Get number of matches
Collapse
X
-
Tags: None
-
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()
-
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
-
Originally posted by Smygisw00t, no python highlighting for the code?
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
Comment