Skip to content Skip to sidebar Skip to footer

Regex To Match A Capturing Group One Or More Times

I'm trying to match pair of digits in a string and capture them in groups, however i seem to be only able to capture the last group. Regex: (\d\d){1,3} Input String: 123456 789101

Solution 1:

You cannot do that using just a single regular expression. It is a special case of counting, which you cannot do with just a regex pattern. \d\d will get you:

Group1: 12 Group2: 23 Group3: 34 ...

regex library in python comes with a non-overlapping routine namely re.findall() that does the trick. as in:

     re.findall('\d\d', '123456')

will return ['12', '34', '56']

Solution 2:

Solution 3:

Try this:

import re
re.findall(r'\d\d','123456')

Solution 4:

Is this what you want ? :

importreregx= re.compile('(?:(?<= )|(?<=\A)|(?<=\r)|(?<=\n))''(\d\d)(\d\d)?(\d\d)?''(?= |\Z|\r|\n)')

for s in('   112233  58975  6677  981  897899\r',
          '\n123456 4433 789101 41586 56 21365899 362547\n',
          '0101 456899 1 7895'):
    print repr(s),'\n',regx.findall(s),'\n'

result

'   112233  58975  6677  981  897899\r' 
[('11', '22', '33'), ('66', '77', ''), ('89', '78', '99')] 

'\n123456 4433 789101 41586 56 21365899 362547\n' 
[('12', '34', '56'), ('44', '33', ''), ('78', '91', '01'), ('56', '', ''), ('36', '25', '47')] 

'0101 456899 1 7895' 
[('01', '01', ''), ('45', '68', '99'), ('78', '95', '')] 

Post a Comment for "Regex To Match A Capturing Group One Or More Times"