Python re.sub 没有返回预期的 int 字符串

标签 python regex

我想在字符串中的数字前补零。例如,字符串

hello120_c

填充到5位数应该变成

hello00120_c

我想使用 re.sub 进行替换。这是我的代码:

>>> re.sub('(\d+)', r'\1'.zfill(5), 'hello120_c')

返回

>>> 'hello000120_c'

有 6 位而不是 5 位。单独检查 '120'.zfill(5) 会得到 '00120'。此外,re.findall 似乎确认正则表达式匹配完整的 '120'

是什么导致 re.sub 行为不同?

最佳答案

您不能直接使用反向引用。使用 lambda :

re.sub(r'\d+', lambda x: x.group(0).zfill(5), 'hello120_c')
# => hello00120_c

另请注意,您不需要捕获组,因为您可以通过 .group(0) 访问匹配的值。另外,请注意用于声明正则表达式的 r'...'(原始字符串文字)。

参见 IDEONE demo :

import re
res = re.sub(r'\d+', lambda x: x.group(0).zfill(5), 'hello120_c')
print(res)

关于Python re.sub 没有返回预期的 int 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920943/

相关文章:

regex - 如何在awk中打​​印没有字段分隔符的行?

用于检查 C 代码括号的正则表达式

javascript - 正则表达式改进

javascript - 获取光标正在触摸(或在其中)JavaScript 的完整单词

javascript - 如何从 url 字符串中删除特定值

python - libnotify 通知控制台,而不是 $DISPLAY?

python - 为什么我的函数落后一键运行?

python - 如何在python中使用正则表达式查找特定格式的值,包括括号

python - pandas 数据框滚动窗口中的最大日期

python - 来自 Pandas Dataframe 的 Sum、Cumsum、Percetage、Cum Percentage