re.compile理解

意思:

  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可以重复进行想要的操作

posted @ 2020-03-03 14:37  Lovange  阅读(832)  评论(0)    收藏  举报