python3正则-编译和其他

发布时间 2023-04-15 12:50:31作者: 挖洞404

1、介绍

将作为pattern参数的str类型,编译返回Pattern类型,方便后续调用,提高效率。

re模块下存在多个函数,可以进行编译,返回类型是Pattern。Pattern类具有和re正则匹配函数类似的方法,当然在参数上略有不同,比如是将待匹配文本作为Pattern类的参数。

2、compile函数

pattern = re.compile("abc")
result = pattern.findall("abcdefabc")
print(result)
print(type(result))
"""
['abc', 'abc']
<class 'list'>
"""

3、purge函数

def purge():
    "Clear the regular expression caches"
    _cache.clear()
    _compile_repl.cache_clear()
  • 作用是净化、清除正则表达式缓存

4、escape函数

  • 参数是str类型,返回类型也是str,作用是处理文本并返回
  • 将参数中可能解读为正则表达式敏感字符的字符进行标记,添加前缀\字符。这样处理之后,在正则匹配时,只会将这些敏感字符连同前面的前缀\视为一个普通的文本字符。
  • 一般用于pattern中,想要表示某部分仅是普通文本而非表达式结构时使用的,当然也可以考虑手动转换和使用[]
s = re.escape("\\abc\n[0-9]")
print(type(s))
print(len(s))
print(s)
"""
<class 'str'>
15
\\abc\
\[0\-9\]
"""

5、template函数

def template(pattern, flags=0):
    "Compile a template pattern, returning a Pattern object"
    return _compile(pattern, flags|T)
  • 该函数和compile函数的参数一样,返回类型也相同,区别在于如果会默认设置flags为T