Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex, match more than one integer

Tags:

python

regex

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
like image 940
chris Avatar asked Aug 25 '26 18:08

chris


2 Answers

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

like image 62
Tomalak Avatar answered Aug 28 '26 07:08

Tomalak


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.
like image 29
Senthil Kumaran Avatar answered Aug 28 '26 07:08

Senthil Kumaran