Skip to main content
 首页 » 编程设计

Python 正则表达式部分不区分大小写

2025年05月04日31lidabo

如何以简洁的方式做到这一点?我有 2 个字符串,我想逐个搜索,但是:

  • lowercase letter matches to lower- and uppercase
  • uppercase letter matches only to uppercase.

例子:

"abcd" 匹配 "AbCd"、"ABCD" 或 "abcd"

"Abcd" 匹配"Abcd"、"ABcd" 等,但不匹配"abcd"

请您参考如下方法:

你需要转换你的正则表达式,比如

def transform(regex): 
    return ''.join([ 
        "[%s%s]" % (c, c.upper()) 
            if c.islower() 
            else c 
        for c in regex 
    ]) 
 
 
transformed = transform('Abcd') 

将正则表达式 Abcd 转换为 A[bB][cC][dD]。

当然,如果您的实际正则表达式已经具有字符类 [a-z],那么这 是行不通的。