正则表达式以所需格式转换给定数字

时间:2019-01-17 11:40:40

标签: python regex python-2.7

我是第一次使用正则表达式,因此需要一个稍微复杂的正则表达式的帮助。我有大约100-150个字符串对象(数字)的输入列表。

input = ['90-10-07457', '000480087800784', '001-713-0926', '12-710-8197', '1-345-1715', '9-23-4532', '000200007100272']

Expected output = ['00090-00010-07457', '000480087800784', '00001-00713-00926', '00012-00710-08197', '00001-00345-01715', '00009-00023-04532', '000200007100272']

## I have tried this -

import re
new_list = []
for i in range (0, len(input)):
    new_list.append(re.sub('\d+-\d+-\d+','0000\\1', input[i]))

## problem is with second argument '0000\\1'. I know its wrong but unable to solve
print(new_list)  ## new_list is the expected output.

如您所见,我需要通过将前导零添加到不同格式的数字字符串转换为15位数字。

但是这里有问题,即某些数字,例如'000480087800784'已经是15位数字,因此应保持不变(这就是为什么我不能使用python的字符串格式(.format)选项)Regex必须在这里使用,这将仅修改所需的数字。我已经尝试过以下答案,但无法解决。

2 个答案:

答案 0 :(得分:1)

您的正则表达式不能像您在替换中使用\1那样工作,但是正则表达式模式没有相应的捕获组。 \1指的是模式中的第一个捕获组。

如果您想尝试使用正则表达式,可以使用

re.sub(r'^(\d+)-(\d+)-(\d+)$', lambda x: "{}-{}-{}".format(x.group(1).zfill(5), x.group(2).zfill(5), x.group(3).zfill(5)), input[i])

请参见Python demo

在这里,^(\d+)-(\d+)-(\d+)$匹配以1+数字开头的字符串,然后是-,然后是1+数字,-,再是1+数字,然后是字符串的末尾。有三个捕获组,其值可以用替换模式中的\1\2\3反向引用来引用。但是,由于我们需要在每个捕获的文本上应用.zfill(5),因此将lambda表达式用作替换参数,并通过匹配数据对象group()方法访问捕获。

但是,如果您的字符串已经采用正确的格式,则可以根据需要拆分字符串和格式:

for i in range (0, len(input)):
    splits = input[i].split('-')
    if len(splits) == 1:
        new_list.append(input[i])
    else:
        new_list.append("{}-{}-{}".format(splits[0].zfill(5), splits[1].zfill(5), splits[2].zfill(5)))

请参见another Python demo。两种解决方案都产生

['00090-00010-07457', '000480087800784', '00001-00713-00926', '00012-00710-08197', '00001-00345-01715', '00009-00023-04532', '000200007100272']

答案 1 :(得分:0)

如何分析字符串中的数字和破折号,然后添加前导零?

input = ['90-10-07457', '000480087800784', '001-713-0926', '12-710-8197', '1-345-1715', '9-23-4532', '000200007100272']
output = []
for inp in input:
    # calculate length of string
    inpLen = len(inp)
    # calculate num of dashes
    inpDashes = inp.count('-')
    # add specific number of leading zeros
    zeros = "0" * (15-(inpLen-inpDashes))
    output.append(zeros + inp)
print (output)

>>> ['00000090-10-07457', '000480087800784', '00000001-713-0926', '00000012-710-8197', '00000001-345-1715', '000000009-23-4532', '000200007100272']