1

This is so far what has been my progress with this regex function :

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)

First do a for loop and look for files in (dpath), then pass the directory name string to replace(). But I am getting missing argument 'string' error :

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'
4
  • re.sub takes three arguments, you've given it two. Commented Jan 14, 2016 at 4:56
  • m = re.sub(fmatch,df, pmatch) Commented Jan 14, 2016 at 5:08
  • I've tried what @AvinashRaj has said before, but when I do I get : File "/usr/lib/python3.4/re.py", line 179, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer Commented Jan 14, 2016 at 5:25
  • think pmatch is not a string.. Commented Jan 14, 2016 at 5:30

2 Answers 2

1

It seems that you want to replace alls all matches of the RegEx \s+[\[]+[A-Z]+[\]]+ to [FLAC]

Make sure you do the following:

def replace(pmatch,df):
    m = fmatch.sub('[FLAC]', df)
    print (m)
Sign up to request clarification or add additional context in comments.

Comments

0

Using @martin-konecny 's Example,

I got this that worked.

Create Files for Example

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

Run Python

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)

Result:

# ...
# [REDACTED]
# [REDACTED]
# ...

Great if you want to run a search and keep a selection of your results secret.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.