Diamond
Diamond

Reputation: 157

Python regular expression searching for a number

I'm new to regex, but looking through a string to find whether or not a pattern exists.

I've tried using the following python code:

prog=re.compile('555.555.555')
m=prog.match(somestring)
if m: print somestring

I'm trying to find 3 groups of 5's separated by any number. This code doesn't return what I'm looking for though.

Any suggestions?

Edit:

Here's some code to test a more basic version:

i,found=0,0
while found==0:
    istr=str(i)
    prog=re.compile(r'1\d2\d3')
    m=prog.search(istr)
    if m:
        print i
        found=1
        break
    i=i+1

This returns 1312 rather than 10203

Upvotes: 0

Views: 149

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

Your regex is OK (sort of), but you're using it wrong. You need

m = prog.search(somestring)

or the regex will only find a match if it is at the beginning of the string.

Also, if you really only want to allow a single digit between each group of 555s, use

prog = re.compile(r'555\d555\d555')

Upvotes: 5

Related Questions