首页 > 解决方案 > RegEx 用于字母数字文本字符串直至特殊模式

问题描述

我有一个具有特定格式的字符串列表,只需要这些元素的一部分。

输入

my_list = ['The Price Is Right S47E141 720p WEB x264-W4F', 'Breakthrough-The Ideas That Changed the World S01E01 480p x264-mSD',
'The Kid Who Would Be King 2019 DVDR-JFKDVD', 'American Housewife S03E18 Phone Free Day 1080p AMZN WEB-DL DDP5 1 H 264-NTb',
'VICE News Tonight 2019 04 16 720p AMZN WEB-DL DDP2 0 H 264-monkee','The Flash 2014 S05E18 Godspeed 720p AMZN WEB-DL DDP5 1 H 264-NTb',
'The Rachel Maddow Show 2019 04 16 720p MNBC WEB-DL AAC2 0 x264-BTW','Lets Make A Deal 2009 S10E142 XviD-AFG']

正则表达式尝试:

try:
    try:
        def get_rls(t):
            w = re.match(".*\d{4} \d{2} \d{2} ", t)
            # w = re.match(".*S\d+E\d+", t)
            if not w: raise Exception("Error For Regular Expression")
            return w.group(0)

        regular_case = [my_list ]
        for w in regular_case:
            Regular_part = get_rls(w)
            print(">>>> Movie Regular Part contains Year/Mon/Day : ", Regular_part)         
    except:
        try:
            def get_rls(t):
                # w = re.match(".*\d ", t)
                w = re.match(".*S\d+E\d+", t)
                if not w: raise Exception("Error For Regular Expression")
                return w.group(0)


            regular_case = [my_list ]
            for w in regular_case:
                Regular_part = get_rls(w)
                print(">>>> Movie Regular Part contains S0E0 : ", Regular_part)             

        except:
            def get_rls(t):
                w = re.match(".*\d{4} ", t)
                # w = re.match(".*S\d+E\d+", t)
                if not w: raise Exception("Error For Regular Expression")
                return w.group(0)


            regular_case = [my_list ]
            for w in regular_case:
                Regular_part = get_rls(w)
                print(">>>> Movie Regular Part contains Year : ", Regular_part)

except:
    print(">>>> Weard Release Name! Pass the Regular part ")
    Regular_part = my_list 

问题是,我的正则表达式代码只能获取一个元素并决定使用哪个正则表达式有用并打印正则表达式,我需要正则表达式代码能够获取列表并处理每个元素,例如获取第一个元素和决定哪个好。

最好的结果应该像下面的列表:

my_list = ['The Price Is Right S47E141', 'Breakthrough-The Ideas That Changed the World S01E01',
'The Kid Who Would Be King 2019 DVDR-JFKDVD', 'American Housewife S03E18 ',
'VICE News Tonight 2019 04 16','The Flash 2014 S05E18',
'The Rachel Maddow Show 2019 04 16 ','Lets Make A Deal 2009 S10E142']

标签: pythonregex

解决方案


这个正则表达式不是完整的正确答案,但它可能会帮助您找出处理文本输入的一般方法。也许,RegEx 不是解决这个问题的最好方法:

^.+?(?:[SE0-9]+)|(?:\s[A-Z]{4}\-[A-Z]{1,})|(?:.+[0-9]{4}\s[0-9]{2}\s[0-9]{2})|(?:\s[SE0-9]{6,10})

在此处输入图像描述

SE这个 RegEx 的模式和date模式很简单。2014您可能面临的问题是您可能会考虑的随机年份,例如20092019


推荐阅读