python - 使用正则表达式在 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()
这里表现的技术原因感到好奇。
解决方案
您会得到该结果,因为该模式,([0-9]),
匹配逗号、单个数字、逗号。在此字符串中(您还添加了逗号),0,1,2,3,4,5,6,7,8,
,它只能匹配,0,
,然后,2,
等等......
要使用单个前导空格填充单个数字,您可以简化脚本,省略使用条带和附加逗号,并使用正向前瞻模式代替。
注意使用量词{1}
可以省略。
,([0-9])(?=,)
例如
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
推荐阅读
- django - 当 proxy_set_header 设置为 $host 时 NGINX 不起作用
- regex - 非捕获组仍在选择元逃生
- java - 给定一组数据,检查它是否是二叉搜索树?
- c# - 剑道网格客户端模板输入隐藏字段单击后变为可编辑
- typo3 - 将变量传递给包含 tx_news 插件的内容对象
- python - 如果满足特定条件,则将字符串与列表列表连接
- heroku - Heroku 不会运行他们的示例 sinatra 应用程序,错误是 bundler: failed to load command: rackup
- docker - 使用 kerberose(GSSAPI)SASL 设置设置 kafka 代理的最佳方法是什么?
- typescript - 打字稿地图键自动完成
- r - 打开在单独选项卡中选择的行