将字符串传递给sub.re不能在Python中工作

时间:2016-01-14 04:54:24

标签: 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()。但是我错过了参数'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'

2 个答案:

答案 0 :(得分:0)

您似乎想要将RegEx \s+[\[]+[A-Z]+[\]]+的所有匹配替换为[FLAC]

确保执行以下操作:

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

答案 1 :(得分:0)

使用@ martin-konecny的示例,

我明白了。

创建示例文件

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:template match="root/ele">
        <names>
            <xsl:value-of select="concat(substring(@name, 1, 1), ' ', substring-after(@name, ' '))"/>
         </names>
    </xsl:template>
</xsl:stylesheet>

运行Python

# Run this in your Shell/Terminal
touch /tmp/abc.FLAC
touch /tmp/abcd.FLAC

结果:

import re
import os

dpath = '/tmp/'

fmatch = re.compile(r'.+\.FLAC')
pmatch = fmatch.match('[FLAC]')


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


def regex(dpath):
    for df in os.listdir(dpath):
        replace(pmatch, df)


regex(dpath)

如果您想进行搜索并秘密选择搜索结果,那就太好了。