Reputation: 1309
In Python is there are easy way to extract strings that look like paths from larger strings?
For example, if:
A = "This Is A String With A /Linux/Path"
What On my way! Looking to extract is:
"/Linux/Path"
I'd also like it to be OS independent, so if:
A = "This is A String With A C:\Windows\Path"
I'd like to extract:
"C:\Windows\Path"
I'm guessing there is a way of doing it with regular expressions looking for /
or \
but I just wondered if there was a more pythonic way?
I'm happy to take the risk that /
or \
may exist in another part of the main string.
Upvotes: 2
Views: 377
Reputation: 85482
You can split at os.sep
and take the results that are longer than one:
import os
def get_paths(s, sep=os.sep):
return [x for x in s.split() if len(x.split(sep)) > 1]
On Linux / OSX:
>>> A = "This Is A String With A /Linux/Path"
>>> get_paths(A)
['/Linux/Path']
For multiple paths:
>>> B = "This Is A String With A /Linux/Path and /Another/Linux/Path"
>>> get_paths(B)
['/Linux/Path', '/Another/Linux/Path']
Mocking Windows:
>>> W = r"This is A String With A C:\Windows\Path"
>>> get_paths(W, sep='\\')
['C:\\Windows\\Path']
Upvotes: 2