使用正则表达式将数字从右到左分成三位一组 [英] Splitting digits into groups of threes, from right to left using regular expressions

查看:283
本文介绍了使用正则表达式将数字从右到左分成三位一组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串'1234567890',我希望将其分成三组,从右到左开始,最左边的组从一位到三位(取决于剩余的位数)

从本质上讲,这与将逗号添加到一个长数字上的过程相同,除了,我也想提取最后三位数字.

我尝试使用环顾四周方法,但找不到最后三种方法 数字.

string = '1234567890'
re.compile(r'\d{1,3}(?=(?:\d{3})+$)')
re.findall(pattern, string)

['1', '234', '567']

预期输出为(我不需要逗号):

 ['1', '234', '567', 789]

解决方案

赞赏的是,如果我们从右到左添加逗号,那么对于每组三个完整数字,我们可以简单地用正则表达式将所有三个数字替换为三位数字后跟一个逗号.在下面的代码片段中,我反转数字字符串,做逗号运算,然后再次反转以获得所需的输出.

string = '1234567890'
string = re.sub(r'(?=\d{4})(\d{3})', r'\1,', string[::-1])[::-1]
print string.split(',')
string = '123456789'
string = re.sub(r'(?=\d{4})(\d{3})', r'\1,', string[::-1])[::-1]
print string.split(',')

输出:

['1', '234', '567', '890']
['123', '456', '789']

用于替换的正则表达式的一部分可能需要进一步说明.我在模式的开头添加了正向前行(?=\d{4}).这样做是为了确保在出现的最后三位数之后,我们不要添加逗号.

此处演示:

妊娠

I have a string '1234567890' that I want split into groups of threes, starting from right to left, with the left most group ranging from one digit to 3-digits (depending on how many digits are left over)

Essentially, it's the same procedure as adding commas to a long number, except, I also want to extract the last three digits as well.

I tried using look-arounds but couldn't figure out a way to get the last three digits.

string = '1234567890'
re.compile(r'\d{1,3}(?=(?:\d{3})+$)')
re.findall(pattern, string)

['1', '234', '567']

Expected output is (I don't need commas):

 ['1', '234', '567', 789]

解决方案

Appreciate that if we add commas from right to left, for each group of three complete digits, then we can simply do a regex replace all of three digits with those three digits followed by a comma. In the code snippet below, I reverse the numbers string, do the comma work, then reverse again to arrive at the output we want.

string = '1234567890'
string = re.sub(r'(?=\d{4})(\d{3})', r'\1,', string[::-1])[::-1]
print string.split(',')
string = '123456789'
string = re.sub(r'(?=\d{4})(\d{3})', r'\1,', string[::-1])[::-1]
print string.split(',')

Output:

['1', '234', '567', '890']
['123', '456', '789']

One part of the regex used for replacement might warrant further explanation. I added a positive lookahead (?=\d{4}) to the start of the pattern. This is there to ensure that we don't add a comma after a final group of three digits, should that occur.

Demo here:

Rextester

这篇关于使用正则表达式将数字从右到左分成三位一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆