意思:
Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions.
目的: 转化成可操作的对象 (用于: 查找匹配 | 替换), 可重复使用
例子:
- import re
- com = re.compile('[Pp]ython')
- def print_obj(obj):
- #Verify whether the string is found.
- if obj:
- print("Pattern found!")
- else:
- print("Pattern not found!")
- string1 = 'Python crash course'
- obj1 = com.match(string1)
- print_obj(obj1)
- print("*" * 20)
- string2 = 'Java crash course'
- obj2 = com.search(string2)
- print_obj(obj2)
re.compile 和正则表达式直接匹配的区别
正则表达式每次使用会直接转换, 使用 re.compile 可以重复进行想要的操作
来源: http://www.bubuko.com/infodetail-3445519.html