简体   繁体   中英

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

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 555 s, use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM