【问题标题】:Regexp is working regex101.com but not in python正则表达式正在使用 regex101.com 但不在 python 中
【发布时间】:2017-02-08 02:25:40
【问题描述】:

我正在尝试创建一个函数,该函数获取一组文件夹名称和一个数字(该函数应返回哪个季节文件夹),并且我想检查是否有一个具有正确季节编号的文件夹 [Staffel = Season in German] 但我不只是拥有简单的英语电视节目,所以我的文件夹命名为 Staffel == German TV Show,如果它的 Eng 则为 Season。

在此示例中,文件夹将包含不同的文件夹 (d) 我正在寻找 (Season|Staffel) 2 它应该返回 Season 02,因为它出现在数组中的 Staffel 2 之前

def findFolderbyNumber(path, number):
    d = getFolders(path)
    d = ['Staffel 1','Staffel 20','Season 02', 'Staffel 2', 'Season 3']
    number = 2
    for obj in d:
        pattern = '(.*)(Staffel|Season)((\s?)*)((0?)*)('+str(number)+')(\D)(.*)'
        m = re.match(pattern, obj)
        print(obj, end='\tMatch = ')
        print(m)
        if(m):
            return obj
    return 0


Staffel 1   Match = None
Staffel 20  Match = None
Season 02   Match = None
Staffel 2   Match = None
Season 3    Match = None

【问题讨论】:

  • \D 匹配非数字字符。您的所有样本都没有 2 后跟非数字字符。
  • 没有它会返回 Staffel 20,我该如何解决?我认为 \D 会做到这一点:D
  • 听起来你想要一个单词边界 (\b)。
  • (?!\d)替换\D
  • 感谢wiktor 成功了! :)

标签: python regex


【解决方案1】:

您需要将最后一个\D 替换为(?!\d)

在您的测试中,您使用了多行字符串输入,并且在代码中,您测试了在 2 之后末尾没有数字的单个字符串。 \D 是消费模式,必须有非数字字符,(?!\d) 是负前瞻,非消费模式,只要求下一个字符不能是数字。

另一种解决方案是将最后一个\D 替换为单词边界\b,但您必须使用原始字符串文字以避免转义问题(即使用r'pattern')。

【讨论】:

    猜你喜欢
    • 2017-01-30
    相关资源
    最近更新 更多