Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...