What's the regular expression pattern that matches the part of a comma-separated number starting from leftmost comma to the last whole number digit

Viewed 99

Given a comma delimited number "123,456,789" as a string, i am attempting build a regular expression pattern that matches from (includes) the left-most comma ',' to the last whole number (unit place value) digit '9'. For the number in the above string, ",456,789" should be matched.

My code goes as followes:

import re
print(re.findall(r"(,\d{3})*", "123,456,789"))
# The above regular expression pattern is actually part of a much larger
# regular expression pattern to match a number that may or may not be
# comma delimited or be in scientific notation. The pattern is:
# r"([-+]?\d+){1}(,\d{3})*(\.\d+)?([Ee][+-]?([-+]?\d+){1}(,\d{3})*)?"

The above code however produces a logic error where only the minimal (non-greedy) right-most match is returned. The output is as follows:

In [0]: print(re.findall(r"(,\d{3})*", "123,456")) # Expected output: ',456'
Out[0]: [',456', '']

In [1]: print(re.findall(r"(,\d{3})*", "123,456,789")) # Expected output: ',456,789'
Out[1]: [',789', '']

In [2]: print(re.findall(r"(,\d{3})*", "123,456,789,000")) # Expected output: ',456,789,000'
Out[2]: [',000', '']

Please help me identify my mistake.

2 Answers

Use regex start of string \A to find the first match only.

number = '123,456,789'
all_after_first_comma = re.sub('\A\d{1,3},', ',', number)

to get ',456,789'

You can simply add a ?: to your pattern to suppress the subgroups, making the pattern (?:,\d{3})*:

import re

for result in filter(None, re.findall("(?:,\d{3})*", "123,456,789")):
    print(result)

Output:

,456,789

The filter is there to filter out empty strings.

Related