Regular Expression over a file path to match file names that don't start with some word

Viewed 210

In a text containing lines with full paths, I need to match only lines whose file name doesn't start with the word 'TMP' (case insensitive).

In the next sample list, lines marked with "EXCLUDE" shouldn't be matched.

c:\folder1\TMP_file.ext----------EXCLUDE
c:\TMP_folder1\file.ext
c:\folder1\TMP_folder2\file.ext
c:\folder1/TMP_file.ext----------EXCLUDE
c:\file.ext
c:\TMP_file.ext------------------EXCLUDE
TMP_file.ext---------------------EXCLUDE
file.ext

I came up with the simple expression [^\\/\r\n]+$ (accepting '\' and '/' as directory separators) that successfully matches whole file names with their extensions, but I can't figure out how to add (?!...) to exclude the matches that start with 'tmp'.

Inverting the expression tmp[^\\/\r\n]+$ would be also the solution, but I don't know how.

I know this question is similar to others (taking the risk of a downvote...) but I didn't found a way to connect them with this problem.

2 Answers

Regex is not the right solution here. You better iterate over file names, takes the base path, and skip if it startswith 'TMP'.

def filter_tmp(text):
    paths = text.split('\n')
    for p in paths:
        if not os.path.basename(p).startswith('TMP'):
            yield p

Then list(filter_tmp(text)) would give you the list of non-temp paths.

You can use

(?i)^(?!(?:.*[/\\])?TMP(?![^\W_])[^/]*$).+

See the regex demo ([^/] is replaced with [^/\n] since the regex is tested against a single multiline string).

Details

  • ^ - start of string
  • (?!(?:.*[/\\])?TMP(?![^\W_])[^/]*$) - a negative lookahead that fails the match if, immediately to the right of the current location, there is
    • (?:.*[/\\])? - an optional occurrence of any 0+ chars other than line break chars as many as possible and then / or \
    • TMP(?![^\W_]) - TMP (case insensitive) not followed with a letter or digit (can be followed with _)
    • [^/]* - any 0 or more chars other than /
    • $ - end of string.
  • .+ - one or more chars other than line break chars.
Related