在Python中是否可能实现类似这个简单的东西:
#!/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等等)
在Python中是否可能实现类似这个简单的东西:
#!/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等等)
>>> import re
>>> regex = re.compile('(?i:use)\s+([A-Z0-9]+)\s+(?i:code)')
>>> regex.match('Use HELLO1 code')
<_sre.SRE_Match object; span=(0, 15), match='Use HELLO1 code'>
>>> regex.match('use HELLO1 Code')
<_sre.SRE_Match object; span=(0, 15), match='use HELLO1 Code'>
#! /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
re
的替代品。 - Endre Both(?imsx-imsx:...)
的文档?我只在help(re)
中看到(?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below)
。 - Shuzheng