2016-04-18 34 views
1

Pythonでは、大きな文字列からのパスのように見える文字列を簡単に抽出できますか?文字列のようなパスを文字列から抽出する

たとえば、:

A = "This Is A String With A /Linux/Path" 

何私の方法で!抽出するために探している:

"/Linux/Path" 

ので、もし私もそれは、OSに依存しないようにしたいよう:私は抽出したい

A = "This is A String With A C:\Windows\Path" 

"C:\Windows\Path" 

私は/または\を探している正規表現でそれを行う方法があると推測していますが、もっとpythonicな方法があるのか​​どうか疑問に思っています。

/または\がメインストリングの別の部分に存在する可能性があります。

答えて

1

あなたはos.sepで分割し、1よりも長く、結果取ることができます。Linux/OSX上で

import os 

def get_paths(s, sep=os.sep): 
    return [x for x in s.split() if len(x.split(sep)) > 1] 

>>> A = "This Is A String With A /Linux/Path" 
>>> get_paths(A) 
['/Linux/Path'] 

複数のパスの場合:

>>> B = "This Is A String With A /Linux/Path and /Another/Linux/Path" 
>>> get_paths(B) 
['/Linux/Path', '/Another/Linux/Path'] 

モッキングをWindows:

>>> W = r"This is A String With A C:\Windows\Path" 
>>> get_paths(W, sep='\\') 
['C:\\Windows\\Path'] 
+0

お返事ありがとうございます。 – Mark

関連する問題