重新编译如何工作

时间:2019-04-29 01:49:15

标签: python regex compilation

下面的re.compile函数让我有些困惑,我知道它可以编译以检测所有不可打印的字符。但我不确定放在编译函数中的参数的含义。谢谢你们!

re_print = re.compile('[^%s]' % re.escape(string.printable))

1 个答案:

答案 0 :(得分:1)

简化一下,看看是否有帮助。在python3解释器中运行以下代码:

import string
import re

# This will be the contents of the variable referenced
print(string.printable)

# This is what happens after all those characters are escaped by re
print(re.escape(string.printable)

# This is the whole value you are giving to re.compile (the re_print):
 print('[^%s]' % re.escape(string.printable))
# Note the ^ in front means anything NOT printables

re_print可能用于检查某些文本中的不可打印字符(不在string.printable中),但是其中某些字符需要转义,否则,re将无法获得预期的结果,因为特殊字符可能是解释为正则表达式。

相关问题