Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex search: repeated digit n times

I don't understand why this won't return a match for the repeating digits:

import re
digits = '122223456789'
re.search(r'(\d)\4', digits)

Instead, I get "error: invalid group reference at position 4"

like image 240
Bryce F Avatar asked Feb 07 '17 18:02

Bryce F


1 Answers

Because \4 is a group reference in python-regex engine. If you want to specify a repetition you should use {}.

re.search(r'(\d){4}', digits)

Or if you want to match 4 repeated digit you need to reference it with \1 since (\d) is the first captured-group.

re.search(r'(\d)\1{3}', digits)

Demo:

In [5]: re.search(r'(\d)\1{3}', digits).group(0)
Out[5]: '2222'

You can pass the group number to group() attribute of search() function in order to get the result of matched string by a specific group. Or just pass 0 to get the whole matched.

like image 88
Mazdak Avatar answered Oct 10 '22 23:10

Mazdak