如何在 Python 中为部分正则表达式设置 ignorecase 标志? [英] How to set ignorecase flag for part of regular expression in Python?

查看:46
本文介绍了如何在 Python 中为部分正则表达式设置 ignorecase 标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在 Python 中实现像这样简单的东西:

Is it possible to implement in Python something like this simple one:

#!/usr/bin/perl
my $a = 'Use HELLO1 code';
if($a =~ /(?i:use)\s+([A-Z0-9]+)\s+(?i:code)/){
    print "$1\n";
}

字符串中间的标记字母总是大写.其余单词的字母可以有任何大小写(USE、use、Use、CODE、code、Code等)

Letters of token in the middle of string are always capital. Letters of the rest of words can have any case (USE, use, Use, CODE, code, Code and so on)

推荐答案

据我所知,python 正则表达式引擎不支持部分忽略大小写.这是一个使用不区分大小写的正则表达式的解决方案,然后测试令牌是否为大写.

As far as I could find, the python regular expression engine does not support partial ignore-case. Here is a solution using a case-insensitive regular expression, which then tests if the token is uppercase afterward.

#! /usr/bin/env python

import re

token_re = re.compile(r'use\s+([a-z0-9]+)\s+code', re.IGNORECASE)
def find_token(s):
    m = token_re.search(s)
    if m is not None:
        token = m.group(1)
        if token.isupper():
            return token

if __name__ == '__main__':
    for s in ['Use HELLO1 code',
              'USE hello1 CODE',
              'this does not match',
             ]:
        print s, '->',
        print find_token(s)

这是程序的输出:

Use HELLO1 code -> HELLO1
USE hello1 CODE -> None
this does not match -> None

这篇关于如何在 Python 中为部分正则表达式设置 ignorecase 标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆