Examples:
Some regexes that I have tried:
import re
m = re.search(r"(\d).*?\1", string)
print(m.group(1))
import re
m = re.search(r"(\d)(?!(\d).*?\2).*?\1", string)
print(m.group(1))
One idea: capture the end of the string and add it in the negative lookahead (group 2 here):
(\d)(?=.*?\1(.*))(?!.*?(\d).*?\3.+?\2$)
This way you can control where the subpattern .*?(\d).*?\3
in the negative lookahead ends. If .+?\2$
succeeds, that means there's an other digit that is repeated before the one in group 1.
I anchored the pattern for the regex101 demo with ^.*?
, but you don't need to do that with the re.search
method.
Other way: reverse the string and find the last repeated digit:
re.search(r'^.*(\d).*?\1', string[::-1]).group(1)