正在将字符串传递给sub.We不使用Python

正在将字符串传递给sub.We不使用Python,python,regex,Python,Regex,到目前为止,我使用此正则表达式函数的进展如下: 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.l

到目前为止,我使用此正则表达式函数的进展如下:

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()
。但我遇到缺少参数“string”错误:

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'
root@debian:~#python regex3.py
回溯(最近一次呼叫最后一次):
文件“regex3.py”,第18行,在
正则表达式(dpath)
文件“regex3.py”,第16行,在regex中
更换(pmatch,df)
文件“regex3.py”,第9行,替换
m=re.sub(fmatch,df)
TypeError:sub()缺少1个必需的位置参数:“字符串”

似乎要将正则表达式的所有匹配项替换为
\s+[\[\]+[A-Z]+[\]+
[FLAC]

请确保执行以下操作:

def replace(pmatch,df):
    m = fmatch.sub('[FLAC]', df)
    print (m)

以@martin konecny为例

我找到了一个有效的方法

例如,创建文件
#在Shell/终端中运行此命令
touch/tmp/abc.FLAC
touch/tmp/abcd.FLAC
运行Python
重新导入
导入操作系统
dpath='/tmp/'
fmatch=re.compile(r'.+\.FLAC')
pmatch=fmatch.match(“[FLAC]”)
def更换(P匹配,df):
m=fmatch.sub(“[修订]”,df)
打印(m)
def正则表达式(dpath):
对于os.listdir(dpath)中的df:
更换(pmatch,df)
正则表达式(dpath)
结果:
#。。。
#[修订]
#[修订]
# ...

如果您想运行搜索并对所选结果保密,那就太好了

re.sub
接受三个参数,你给了它两个。
m=re.sub(fmatch,df,pmatch)
我试过@AvinashRaj之前说过的话,但当我这样做时,我得到:
文件/usr/lib/python3.4/re.py”,第179行,在sub返回编译(模式,标志).sub(repl,字符串,计数)类型错误:预期的字符串或缓冲区
认为
pmatch
不是字符串。。