Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - Using regular expression to comma separate a large number in south asian numbering system

I am trying to find a regular expression to comma separate a large number based on the south asian numbering system.

A few examples:

  • 1,000,000 (Arabic) is 10,00,000 (Indian/Hindu/South Asian)
  • 1,000,000,000 (Arabic) is 100,00,00,000 (Indian/H/SA).

The comma pattern repeats for every 7 digits. For example, 1,00,00,000,00,00,000.

From the book Mastering Regular Expressions by Friedl , I have the following regular expression for Arabic numbering system:

r'(?<=d)(?=(d{3})+(?!d))'

For Indian numbering system, I have come up with the following expression but it doesn't work for numbers with more than 8 digits:

r'(?<=d)(?=(((d{2}){0,2}d{3})(?=)))'

Using the above pattern, I get 100000000,00,00,000.

I am using the Python re module (re.sub()). Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I know Tim has answered the question you asked, but assuming you start with numbers rather than strings, have you considered whether you need a regular expression at all? If the machine you are using supported an Indian locale then you could just use the locale module:

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, "en_IN")
'en_IN'
>>> locale.format("%d", 10000000, grouping=True)
'1,00,00,000'

That interpreter session was copied from an Ubuntu system, but be aware that Windows systems may not support a suitable locale (at least mine doesn't), so while this is in some ways a 'cleaner' solution, depending on your environment it may or may not be usable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...