Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 从字符串中提取类似路径的字符串_String_Python 2.7_Substring_Extract - Fatal编程技术网

String 从字符串中提取类似路径的字符串

String 从字符串中提取类似路径的字符串,string,python-2.7,substring,extract,String,Python 2.7,Substring,Extract,在Python中,有没有简单的方法可以从较大的字符串中提取看起来像路径的字符串 例如,如果: A = "This Is A String With A /Linux/Path" 什么在我的路上!希望提取的是: "/Linux/Path" 我还希望它独立于操作系统,因此如果: A = "This is A String With A C:\Windows\Path" 我想摘录: "C:\Windows\Path" 我猜有一种方法可以用正则表达式来查找/或\但我只是想知道是否有一种更符合py

在Python中,有没有简单的方法可以从较大的字符串中提取看起来像路径的字符串

例如,如果:

A = "This Is A String With A /Linux/Path"
什么在我的路上!希望提取的是:

"/Linux/Path"
我还希望它独立于操作系统,因此如果:

A = "This is A String With A C:\Windows\Path"
我想摘录:

"C:\Windows\Path"
我猜有一种方法可以用正则表达式来查找
/
\
但我只是想知道是否有一种更符合python的方法

我很乐意冒着
/
\
可能存在于主字符串的另一部分的风险。

您可以在处拆分,并获取比一个长的结果:

import os

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

>>> 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']
模拟窗口:

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

谢谢你的快速回复-这应该是一种享受!