royskatt
royskatt

Reputation: 1210

Python - Conditional regex matching

Python does unexpectingly not match strings I would like to be matched:

The following function scans a directory for subdirectories, that have a specific name format. If matched, it shall print it out. The regex is correct, I checked it: DEMO.

Still, the conditional block doesn't print out anything, while the print-command before shows, that the directories I am looking for exist. So it should match, but doesn't;

def getRelevantFolders():
    pattern = re.compile('(e|d|b)-(heme|gome|jome)-(?!.*?\/)(.+)')
    for root, dirs, files in os.walk('/jome'):
        print root # f.e.: /jome/stat/d-heme-sdfsdf
        if pattern.match(root):
            print ('Matched: ' + root)

Where is the mistake?

Upvotes: 0

Views: 766

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You need to use re.search instead re.match() because re.match match the pattern from leading :

pattern.search(root)

In python wiki :

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

Upvotes: 2

Daniel
Daniel

Reputation: 42748

Use search instead of match, because match matches always from the beginning of the string.

def getRelevantFolders():
    pattern = re.compile('[edb]-(heme|gome|jome)-([^/]+)')
    for root, dirs, files in os.walk('/jome'):
        print root # f.e.: /jome/stat/d-heme-sdfsdf
        if pattern.search(root):
            print 'Matched: ' + root

Upvotes: 1

Related Questions