6

The below code prints white space and not '11' and I can't figure out why. Replacing [0-9]* with [0-9]{1,2} prints '11'. Can any one help?

import re
test_string = 'cake_11xlfslijg'
pattern = '.*(?P<order>[0-9]*)'
result = re.compile(pattern).search(test_string)
if result:
    print 'result'
    print result.group('order')
else:
    print result
1
  • Replacing [0-9]* with [0-9]{1,2} prints 1, not 11. Commented Jul 20, 2011 at 15:04

4 Answers 4

12

Try [0-9]+. The * translates to "zero or more", and there are zero or more digits right at the start of your string.

Sign up to request clarification or add additional context in comments.

3 Comments

Quick way to show this: re.search('(.*)(\d*)', 'cake11').groups()
This will still only match 1, not 11, because the regex engine backtracks only as far as needed.
@Tim Oh, I've seen the .* only now (that's why I also wrote "at the start of the string" instead of "at the end"). Of course you are right. The regex should be (?P<order>[0-9]+) without the .*.
7

Your regex should be this

pattern = '(?P<order>[0-9]+)'
  1. Removed the first .* as it will do a greedy match of the entire string.
  2. Made [0-9]+ as it will match the digits only even at least one is present, else it will return None.

Comments

1

Because * means: any number of repetitions, in your regex .* will match all the string, because . means any character, i.e. including [0-9]

Comments

0

A regex pattern needs to have a minimum of anchors.

With '.' and '[0-9]' , there are only optional symbols.

Try

import re

for test_string in ( 'cake_11xlfslijg',
                     'cake_uuxlfslijg'):
    pattern = '.*?(?P<order>[0-9]+)'
    result = re.compile(pattern).search(test_string)
    print test_string
    print 'result: ',repr(result.group('order')) if result else result
    print

gives

cake_11xlfslijg
result:  '11'

cake_uuxlfslijg
result:  None

Comments

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.