我正在做Python挑战,虽然我想出了一个难题的答案,但我是以一种老生常谈的、不是很好的方式完成的。在前进的过程中,我能够看到解决方案,即:
string1 = open('text.txt').read()
print ''.join(re.findall('[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]', string1))我处理了一段时间,删除了这里的一个插入符号,看看发生了什么,在那里更改了一个带括号的组。然而,我就是不能理解为什么这样做是可行的。有没有人能用一种简单易懂的方式解释一下?
谢谢!
发布于 2012-06-05 22:09:47
我将该模式编译为verbose,以包括内联注释:
pat = re.compile('''
[^A-Z] # any character except a capital letter
[A-Z]{3} # three capital letters
( # the beginning of a capturing group
[a-z] # one lowercase letter
) # the end of the group
[A-Z]{3} # three capital letters
[^A-Z] # any character except a capital letter
''', re.VERBOSE)演示:
>>> re.findall(pat, 'AAAAaBBBbBBBBzzZZZxXXXyYYYYwWWWvABCn')
['x', 'v']发布于 2012-06-05 22:06:26
([a-z])捕获单个小写字母。
[A-Z]{3}匹配3个大写字母(在两侧)。
[^A-Z]确保没有第四个大写字母(“正好三个”)。
发布于 2012-06-05 22:07:25
^A-Z非大写字母的字符
A-Z{3}三个大写字母
(a-z)匹配的小写字母
重复前两个步骤。
https://stackoverflow.com/questions/10898651
复制相似问题