个人而言,我不使用 re.VERBOSE
,因为我不想转义空格,也不想在 '\s' 不是必需时将其替换为空格。
正则表达式模式中的符号与必须捕获的字符序列相对精确,该正则表达式对象的操作速度就会越快。我几乎从不使用 '\s'
.
要避免使用 re.VERBOSE
,您可以像已经说过的那样做:
test = re.compile(
'(?P<full_path>.+)'
':\d+:\s+warning:\s+Member\s+'
'(?P<member_name>.+)'
'\s+\('
'(?P<member_type>%s)'
'\) of '
'(class|group|namespace)'
'\s+'
'(?P<class_name>.+)'
'\s+is not documented'\
% (self.__MEMBER_TYPES),
re.IGNORECASE)
将字符串向左推可以提供大量的空间来编写注释。
.
但是当模式非常长时,这种方式并不好,因为无法编写
test = re.compile(
'(?P<full_path>.+)'
':\d+:\s+warning:\s+Member\s+'
'(?P<member_name>.+)'
'\s+\('
'(?P<member_type>%s)' % (self.__MEMBER_TYPES)
'\) of '
'(class|group|namespace)'
'\s+'
'(?P<class_name>.+)'
'\s+is not documented',
re.IGNORECASE)
如果要匹配的模式非常长,最后部分% (self.__MEMBER_TYPES)
和应用于其上的字符串'(?P<member_type>%s)'
之间的行数可能会很多,导致模式难以阅读。
.
因此,我喜欢使用元组来编写非常长的模式:
pat = ''.join((
'(?P<full_path>.+)',
':\d+:\s+warning:\s+Member\s+',
'(?P<member_name>.+)',
'\s+\(',
'(?P<member_type>%s)' % (self.__MEMBER_TYPES),
'\) of ',
'(class|group|namespace)',
'\s+',
'(?P<class_name>.+)',
'\s+is not documented'))
这种方式允许将模式定义为一个函数:
def pat(x):
return ''.join((\
'(?P<full_path>.+)',
':\d+:\s+warning:\s+Member\s+',
'(?P<member_name>.+)',
'\s+\(',
'(?P<member_type>%s)' % x ,
'\) of ',
'(class|group|namespace)',
'\s+',
'(?P<class_name>.+)',
'\s+is not documented'))
test = re.compile(pat(self.__MEMBER_TYPES), re.IGNORECASE)
re.VERBOSE
表示在正则表达式中可以包含注释,这样可以增加正则表达式的可读性。 - jfs(?x)
。此外,您还可以使用[ ]
或\
来转义空格。 - jfsre.DEBUG
表示 '编译后转储模式'。 - jfs