这是迄今为止我使用此正则表达式函数的进展:
import os, re
dpath="/root/tree/def/"
fmatch = re.compile(r'\s+''[\[]+''[A-Z]+''[\]]+')
pmatch = fmatch.match('[FLAC]')
def replace(pmatch,df):
m = re.sub(fmatch,df)
print (m)
def regex(dpath):
for df in os.listdir(dpath):
replace(pmatch, df)
regex (dpath)
首先执行 for 循环并在 (dpath)
中查找文件,然后将目录名称字符串传递给 replace()
。但我遇到了缺少参数“字符串”错误:
root@debian:~# python regex3.py
Traceback (most recent call last):
File "regex3.py", line 18, in <module>
regex (dpath)
File "regex3.py", line 16, in regex
replace(pmatch, df)
File "regex3.py", line 9, in replace
m = re.sub(fmatch,df)
TypeError: sub() missing 1 required positional argument: 'string'
最佳答案
您似乎想将正则表达式 \s+[\[]+[A-Z]+[\]]+
的所有匹配项替换为 [FLAC]
确保执行以下操作:
def replace(pmatch,df):
m = fmatch.sub('[FLAC]', df)
print (m)
关于python - 将字符串传递给 sub.re 在 Python 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34781992/