regex = r"([a-zA-Z]+) (\d+)" re.sub(regex, r'\2 of \1', "June 24, August 9, Dec 12") # output: # '24 of June, 9 of August, 12 of Dec'
re Flags
re 模块中每一种匹配方法基本上都有 flags 参数,默认为0.
Flag
意义
re.IGNORECASE
不区分大小写
re.MULTILINE
使^和$将\n分开的各行作为行,否则默认是全文
re.DOTALL
使.能够匹配\n
re.RegexObject
需要多次重用相同的pattern匹配时,可以将pattern提前编译,提高运算速度
1
regexObject = re.compile(pattern, flags=0)
regexObject 拥有的方法与之前re的函数基本相同
1 2 3 4 5
regex = re.compile(r'(\w+) World')
result = regex.search('Hello World is the easiest') results = regex.findall('Hello World, Bonjour World') replacedString = regex.sub(r'\1 Earth', 'Hello World')