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

标签 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"

我猜想有一种方法可以用正则表达式来查找 /\ 但我只是想知道是否有更Pythonic的方法?

我很乐意承担 /\ 可能存在于主字符串的其他部分的风险。

最佳答案

您可以通过 os.sep 进行拆分并取长于 1 的结果:

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']

关于string - 从字符串中提取类似字符串的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36702426/

相关文章:

python - Django:通过 send_mass_mail() 发送 HTML 电子邮件

python - 在我的示例中如何访问类外的变量?

c - C中用另一个子字符串替换部分字符串

java - 为什么要编译 Java 正则表达式?

android - strings.xml 中的双引号是做什么用的?

java - 将字符串中的每个单词或数字组合加倍

Python 将 *args 转换为列表

Java 检查字符串可变长度(带子字符串)

c - 查找数组中给定字符的每个位置

javascript - 字符串包含另一个字符串