I am trying to find all the integers of length 3 without iterating ,though they have leading zeros
>>> import re
>>> li = re.findall("[\d+]{3}","abc42h456k678954hars234ok001")
>>> print(li)
['456', '678', '954', '234','001']
I want the regex to consider 678954 as a single integer of length 6 but not two individuals of length 3 . Whats the proper way to do so it should replace the following code
for num in re.findall("\d+","abc42h456k678954hars234ok001"):
if len(num) == 3:
li.append(num)
>Solution :
You can use (?:\D|^)(\d{3})(?:\D|$) to specify the preceding and following character for the pattern to be either non digit character or start / end of string:
li = re.findall("(?:\D|^)(\d{3})(?:\D|$)","abc42h456k678954hars234ok001")
li
# ['456', '234', '001']