python - 将字符串传递给 sub.re 在 Python 中不起作用

标签 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.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/

相关文章:

python - DataGenerator TypeError : unsupported operand type(s) for *: 'generator' and 'float'

python - 在Python中对加速度计数据随时间的变化进行分类

Python - 在 Tkinter 中使用绑定(bind)键移动输入光标

regex - 如何禁用 grep [] 语法中 ^ 字符的特殊含义?

R - 在包含关键字的括号之间提取文本的正则表达式

python - 在python列表中切片一个字符串

python - 对于列表中的多个字符串,如何查找字符串中以大写字母开头的所有单词

regex - 如何为相似字符编写 JPQL 查询

python - Flask:无法解码使用请求提交的传入 JSON

python - 如何使用 BeautifulSoup 发送 key