简体   繁体   中英

Python Regular Expression find repeating digits

I have a Python question imagine variable x below. I want to write a regular expression that helps me finds any repeating single digits. Like 1 is not repeated, but 2 is mentioned twice, and 3 is 3 times.

x='1234328732'#a string of digits

re.search(r'(\d+).*\1', x).group(1) 

this is what I thought, but this just gives me a return of patterns. The above returns nothing cause there is no repeating patterns. But if

x='1231231234' 

it will return 123 But repeating patterns is not what I want. I want repeating digits. So for the first x it should give 2, 3 for the second x it should give 1, 2, 3

This is for learning the RE idea mostly Thx

may be something like this, using Counter() :

>>> import re
>>> from collections import Counter

>>> x='1234328732'
>>> c=Counter(re.findall(r'\d',x))
>>> [x for x in c if c[x]>1]
['3', '2']


>>> x='1231231234' 
>>> c=Counter(re.findall(r'\d',x))
>>> [x for x in c if c[x]>1]
['1', '3', '2']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM