Question

I have a variable which contains a path and I want to extract the 6th folder from the path, but the 7 folder may or may not occur. In both cases... the regex should return "three", but the first example fails to match. I tried using ? to indicate optional, but my attempt was incorrect.

What do I need to change in the regex to make it match in both cases:

path = "//network/path/folder/_one/two/three"  # fails 
path = "//network/path/folder/_one/two/three/four"  # works

p = re.compile('^//network/path/folder/_.*?/.*?/(.*?)/')   # compile the regex
m = re.search(p, path)    # regex search

if m:     # regex matched
    print "6th folder =",m.group(1)
Was it helpful?

Solution

Perhaps you could target lesser characters instead of .*

^//network/path/folder/_.*?/[^/]*/([^/]*)

http://regexr.com?356lh

[^/]* means any number of occurences of any character but NOT A FORWARD SLASH. ^ is not flag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top