Python Forum
Regex: Matches a number with commas for every three digits
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regex: Matches a number with commas for every three digits
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
\D same (?!\d) ? I think don't difficult ?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  print on a single line with start/end brackets and commas Paulman 2 1,804 Oct-23-2021, 10:00 AM
Last Post: Paulman
  Analyzing data seperated by commas Kappel 2 1,845 Aug-07-2019, 01:46 PM
Last Post: ThomasL

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020