0

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?

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.