I need to find all occurrences of 7 consecutive numbers starting and ending with space in python with regex. If the string starts with set of 7 numbers the space before set must be omitted. If the string ends with set of 7 numbers the space after set must be omitted.
str = "1234567 7777777 88888888 9999999 -7654321 555-5555 456456 123.1245 6666666"
Expected output:
["1234567", "7777777", "9999999", "6666666"]
eg
lst = re.findall("\d{7}", str)
Just find all on (?<?\S)\d{7}(?!\S)
:
str = "1234567 7777777 88888888 9999999 -7654321 555-5555 456456 123.1245 6666666"
nums = re.findall(r'(?<!\S)\d{7}(?!\S)', str)
print(nums) # ['1234567', '7777777', '9999999', '6666666']
The regex pattern used here says to:
(?<!\S) assert that whitespace or start of string precedes
\d{7} match a 7 digit number
(?!\S) assert that whitespace or the end of the string follows
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.