0

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

9
  • 2
    You probably want '555\d+555\d+555'? Please clarify with example. Commented Jul 16, 2012 at 14:05
  • What's an example somestring? Commented Jul 16, 2012 at 14:05
  • I guess that you want also to use prog.search not prog.match Commented Jul 16, 2012 at 14:06
  • Example somestring: 12345552152 Commented Jul 16, 2012 at 14:08
  • Small aside: I'd recommend you to read PEP-8. For example, you should surround the assignment operator = with spaces (unless used for keyword arguments). Commented Jul 16, 2012 at 14:10

1 Answer 1

5

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping Tim - see additional information in the description

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.