Python 3.3 中的 re.sub [英] re.sub in Python 3.3

查看:42
本文介绍了Python 3.3 中的 re.sub的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本字符串从 file1 的形式更改为 file01.我对 python 真的很陌生,在尝试使用模式时无法弄清楚repl"位置应该放什么.谁能帮我一把?

text = 'file1 file2 file3'x = re.sub(r'file[1-9]',r'file\0\w',text) #我不确定在 repl 中应该放什么.

解决方案

你可以试试这个:

<预><代码>>>>进口重新>>>文本 = '文件 1 文件 2 文件 3'>>>x = re.sub(r'file([1-9])',r'file0\1',text)'文件01 文件02 文件03'

[1-9] 周围的括号捕获匹配,它是第一个匹配.您将看到我在使用 \1 的替换中使用了它,这意味着匹配中的第一个捕获.

另外,如果您不想为 2 位或更多的文件添加零,您可以在正则表达式中添加 [^\d] :

x = re.sub(r'file([1-9](\s|$))',r'file0\1',text)

<小时>

现在我正在使用 str.format() 和一个 lambda 表达式:

导入重新fmt = '{:03d}' # 假设我们想要 3 个带前导零的数字s = '文件 1 文件 2 文件 3 文本 40'结果 = re.sub(r"([A-Za-z_]+)([0-9]+)", \lambda x: x.group(1) + fmt.format(int(x.group(2))), \s)打印(结果)#'file001 file002 file003 text040'

关于 lambda 表达式的一些细节:

lambda x: x.group(1) + fmt.format(int(x.group(2)))# ^--------^ ^-^ ^------------^# filename 格式文件编号([0-9]+) 转换为int# ([A-Za-z_]+) 所以 format() 可以使用我们的格式

我使用表达式 [A-Za-z_]+ 假设文件名除训练数字外仅包含字母和下划线.如果需要,请选择更合适的表达方式.

I am trying to change the text string from the form of file1 to file01. I am really new to python and can't figure out what should go in 'repl' location when trying to use a pattern. Can anyone give me a hand?

text = 'file1 file2 file3'

x = re.sub(r'file[1-9]',r'file\0\w',text) #I'm not sure what should go in repl.

解决方案

You could try this:

>>> import re    
>>> text = 'file1 file2 file3'
>>> x = re.sub(r'file([1-9])',r'file0\1',text)
'file01 file02 file03'

The brackets wrapped around the [1-9] captures the match, and it is the first match. You will see I used it in the replace using \1 meaning the first catch in the match.

Also, if you don't want to add the zero for files with 2 digits or more, you could add [^\d] in the regexp:

x = re.sub(r'file([1-9](\s|$))',r'file0\1',text)


A bit more of a generic solution now that I'm revisiting this answer using str.format() and a lambda expression:

import re
fmt = '{:03d}'                 # Let's say we want 3 digits with leading zeroes
s = 'file1 file2 file3 text40'
result = re.sub(r"([A-Za-z_]+)([0-9]+)", \
                lambda x: x.group(1) + fmt.format(int(x.group(2))), \
                s)
print(result)
# 'file001 file002 file003 text040'

A bit of details about the lambda expression:

lambda x: x.group(1) + fmt.format(int(x.group(2)))
#         ^--------^   ^-^        ^-------------^
#          filename   format     file number ([0-9]+) converted to int
#        ([A-Za-z_]+)            so format() can work with our format

I am using the expression [A-Za-z_]+ assuming the filename contains letters and underscores only besides the training digits. Do pick a more appropriate expression if required.

这篇关于Python 3.3 中的 re.sub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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