【问题标题】:How to extract the filename from a string using regular expression [duplicate]如何使用正则表达式从字符串中提取文件名[重复]
【发布时间】:2020-01-30 13:33:46
【问题描述】:

我是正则表达式的新手,并试图从基本上是文件路径的字符串中提取文件名。


string = "input_new/survey/argentina-attributes.csv"
string_required = argentina-attributes

我知道我可以通过下面的代码做到这一点。

string.split('/')[2].split('.')[0]

但我希望通过使用正则表达式来做到这一点,所以如果将来路径的格式发生变化(input_new/survey/path/path/argentina-attributes.csv)不应该影响输出。

我知道之前有人问过类似的问题,但我正在寻找一种适用于我的用例的模式。

【问题讨论】:

  • 看看herer'^.*[\\/](.+?)\.[^.]+$' 看起来就是你想要的。
  • 我建议您使用pathlib 库(在std 库中),它用于操作路径并且(在我看来)非常方便。一个简单的Path(string).name 就可以了
  • `>>> re.search(r"^.*[\\/](.+?)\.[^.]+$", "input_new/survey/argentina-attributes. csv").group(0) 'input_new/survey/argentina-attributes.csv' 不工作

标签: python regex python-3.x


【解决方案1】:

试试这个,

>>> import re
>>> string = "input_new/survey/argentina-attributes.csv"

输出:

>>> re.findall(r'[^\/]+(?=\.)',string) # or re.findall(r'([^\/]+)\.',string)
['argentina-attributes']

转自here

【讨论】:

  • 谢谢它的工作。
【解决方案2】:

试试这个:

string = "input_new/survey/argentina-attributes.csv"
new_string = string.split('/')[-1].split('.')[0]
print(new_string)

【讨论】:

  • 谢谢,这会起作用,但是如何使用正则表达式来做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
相关资源
最近更新 更多