【问题标题】:How to check if a string matches a certain pattern?如何检查字符串是否与某个模式匹配?
【发布时间】:2016-10-03 17:55:50
【问题描述】:

我有一个字符串,它基本上是 .mp4 文件的文件路径。

我想测试文件路径是否匹配以下模式之一:

/*.mp4   (nothing before the slash, anything after)
*/*.mp4  (anything before and after the slash)
[!A]*.mp4  (anything before the extension, **except** for the character 'A')

实现这一目标的最佳方法是什么? 谢谢!

编辑:

我不想测试文件是否以 .mp4 结尾,我想测试它是否以它结尾并且分别匹配这 3 个场景中的每一个。

我尝试使用“endswith”,但它过于笼统,无法像我在示例中寻找的那样“具体化”。

【问题讨论】:

  • string.endswith('mp4')?
  • 这是一个概括,我正在寻找一种方法来分别测试上述场景中的每个
  • 阅读re 的文档,用online regex tester 试试运气,编写一些代码。
  • @Gambit2007 这个问题没有显示任何研究工作。见How to Ask
  • 好吧,这真的是我的错。然而人们仍然将此问题标记为重复问题。

标签: python


【解决方案1】:

他们在这里:

string.endswith('.mp4') and string.startswith('/')

string.endswith('.mp4') and "/" in string

string.endswith('.mp4') and "A" not in string

或者,看看使用fnmatch

【讨论】:

  • 只是一个更正 - 为了找到正斜杠,您需要对其进行转义,以便它实际上是 '//'
  • @Gambit2007 不,你不需要逃避它。在大多数系统上,只有反斜杠必须转义。
  • 好的,我正在使用 OS X El Capitan,我不得不逃脱它
  • @wim 为什么将 'A' not in string 更改为 not string.startswith('a') 。似乎与第三个标准不同。另外,为什么 fnmatch 而不是 find
  • 我的错误。改回来了。 fnmatch 是这种 globbing 的常用方法,它可能有助于其他读者提及它。 find 在这里不好,因为它不支持任何通配符。
猜你喜欢
  • 2010-12-19
  • 2012-09-17
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多