Python使用正则
Python中使用正则的两种方式
在Python中有两只能够使用正则表达式的方式:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。- 直接使用re模块中的函数

import re re_string = "{{(.*?)}}" some_string="this is a string with {{words}} enmbedded in {{curly brackets}}.." for match in re.findall(re_string, some_string): print("MATCH->", match) MATCH-> words MATCH-> curly brackets直接使用re模块中的函数
- 创建一个它编译的正式表达式对象,然后使用对象中的方法

import re re_obj = re.compile("{{.*?}}") some_string="this is a string with {{words}} enmbedded in {{curly brackets}}.." for match in re_obj.findall(some_string): print("MATCH->", match) MATCH-> {{words}} MATCH-> {{curly brackets}}使用编译的对象
我们可以根据个人喜好选择使用其中一种正则表达式的方法,然而,使用第二种方法对性能好很多
原始字符串与正则表达式
In [12]: raw_pattern = r'\b[a-z]+\b' In [13]: non_raw_pattern = '\b[a-z]+\b' In [14]: some_string = 'a few little words' In [15]: re.findall(raw_pattern, some_string) Out[15]: ['a', 'few', 'little', 'words'] In [16]: re.findall(non_raw_pattern, some_string) Out[16]: []
正则表达式模式"\b"匹配单词边界。raw_patern匹配了在some_string中合适的单词边界,而non_raw_patter根本没有任何匹配
raw_pattern将"\b"识别为两个字符,而不是解析为转移字符中的退格字符
non_raw_pattern则将"\b"解析为转移字符中的退格字符
findall()
In [19]: import re In [20]: re_obj = re.compile(r'\bt.*?e\b') In [21]: re_obj.findall("tim tame tune tint tire") Out[21]: ['tim tame', 'tune', 'tint tire']
模式没有定义任何组,因此findall()返回一个字符串列表
有趣的是返回列表的

更多精彩