首页 > 解决方案 > 使用正则表达式在 CSV 字符串中填充空格

问题描述

在 Python 中,我试图用正则表达式在 CSV 字符串中填充数字。我当然可以使用 split()、format() 和 join() 来做到这一点,但我的限制是使用正则表达式。为什么以下re.sub仅对找到的匹配项 0、2、4、6、8 进行替换?它跳过了所有其他比赛。

import re

# trying to pad the single-digit numbers in a CSV with a single leading space
# input '1,2,12,14' would produce output ' 1, 2,12,14' (notice leading spaces on single-digit numbers)

s = '0,1,2,3,4,5,6,7,8,9,28,29,30,31,32,33,34,35'
print(s)

# first, add commas to front and end so that first and final numbers are captured by the regex
s = ',' + s + ',' 
# the main regex
s = re.sub(r',([0-9]{1}),', r', \1,', s)
# lastly, strip the front and end commas we added before the regex
s = s.strip(',')
print(s)

...上面产生以下输入字符串和输出字符串:

0,1,2,3,4,5,6,7,8,9,28,29,30,31,32,33,34,35
 0,1, 2,3, 4,5, 6,7, 8,9,28,29,30,31,32,33,34,35

所以我只是对re.sub()这里表现的技术原因感到好奇。

标签: pythonregex

解决方案


您会得到该结果,因为该模式,([0-9]),匹配逗号、单个数字、逗号。在此字符串中(您还添加了逗号),0,1,2,3,4,5,6,7,8,,它只能匹配,0,,然后,2,等等......

要使用单个前导空格填充单个数字,您可以简化脚本,省略使用条带和附加逗号,并使用正向前瞻模式代替。

注意使用量词{1}可以省略。

,([0-9])(?=,)

正则表达式演示| Python 演示

例如

import re
s = '0,1,2,3,4,5,6,7,8,9,28,29,30,31,32,33,34,35'
regex = r',([0-9])(?=,)'
s = re.sub(regex, r', \1', s)
print(s)

输出

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,28,29,30,31,32,33,34,35

如果您还想支持仅填充单个数字,则可以在末尾匹配逗号或断言字符串结尾处更新正向前瞻:

,([0-9])(?=,|$)

正则表达式演示

编辑

由于您还想附加和前置逗号并填充第一个数字,因此您可以将模式更新为(?:,|^)([0-9])(?=,|$)

import re

s = '0,1,2,3,4,5,6,7,8,9,28,29,30,31,32,33,34,35'
s = ',' + s + ','
s = re.sub(r'(?:,|^)([0-9])(?=,|$)', r', \1', s)
s = s.strip(',')
print(s)

输出

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,28,29,30,31,32,33,34,35

Python 演示


推荐阅读