Reputation: 101
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"
Upvotes: 6
Views: 12130
Reputation: 107347
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.
Upvotes: 12