Skip to main content
 首页 » 编程设计

python 正则表达式 : match last instance of character followed by certain parttern

2025年05月04日25Renyi-Fan

我想编辑下面的代码以捕获所有以“_C[任何字母/任何数字/或无]”结尾的字符串

这是我的 list

 name_list = ['chrome_PM', 
             'chrome_P', 
             'chromerocker_C', 
             'chromebike_P1', 
             'chromecar_CMale', 
             'chromeone_C1254', 
             'Lukate_Aids_Consumer_P'] 
 
for name in name_list: 
    counts_tail = re.compile('_C[\da-zA-Z_]*$') 
    if counts_tail.search(name): 
        print name 

输出:

chromerocker_C 
chromecar_CMale 
chromeone_C1254 
Lukate_Aids_Consumer_P 

预期输出:

chromerocker_C 
chromecar_CMale 
chromeone_C1254 

“Lukate_Aids_Consumer_P”不应包含在内,因为它不以“_C”结尾,我该如何编辑我的代码来处理这个错误?

谢谢

请您参考如下方法:

您只需要从最后一个字符类中删除 _。

counts_tail = re.compile('_C[\da-zA-Z_]*$') 
                                     ^ 
                                     | 

所以正确的形式是,

 name_list = ['chrome_PM', 
             'chrome_P', 
             'chromerocker_C', 
             'chromebike_P1', 
             'chromecar_CMale', 
             'chromeone_C1254', 
             'Lukate_Aids_Consumer_P'] 
 
for name in name_list: 
    counts_tail = re.compile('_C[\da-zA-Z]*$') 
    if counts_tail.search(name): 
        print name 

由于 _ 出现在字符类中,它匹配 Lukate_Aids_Consumer_P 中的 _Consumer_P 子串。