Python Forum

Full Version: Regex: Matches a number with commas for every three digits
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello everybody, i am doing my homework, "write a regex that matches a number with commas for every three digits":
This is my code:
import re

numRegex = re.compile(r"((?<!\d)\d{1,3}(?!\d)(,\d{3})*)")
txt = "  ababs123,223,441,112    1234  121,311     12,34,567   12341  1,213 "
xs = numRegex.findall(txt)
for x in xs:
	print(x[0])
all OK except when there are 2 or more numbers between two ",". Ex, 12,34,567 => 12 and 34,567 or 12,3234,567 => 12,323 and 567

anyone help me Sad
I tend to avoid look aheads/behinds in regexes. I think you could do just as well with non-digit matching (\D) outside of your main group. Then match 1 to 3 digits, followed by zero or more instances of a comma and three digits.
\D same (?!\d) ? I think don't difficult ?