re正则模块 |
本节内容:
- 正则介绍
- 元字符及元字符集
- 元字符转义符
- re模块下的常用方法
正则介绍(re) |
正则表达式(或 RE)是一种小型的、高度专业化的编程语言.
在Python中,它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
元字符及元字符集 |
1、元字符之. ^ $ * + ? { }
import re ret = re.findall('o...n', 'oksdaoceanaaaddf') print(ret) # ['ocean'] ret = re.findall('^o...n', 'oceanhelloowwwn') #以o开头的才能匹配上,这里的头是整个字符串的开头 print(ret) # ['ocean'] ret = re.findall('o...n', 'ooceanhelloowwwn') print(ret) # ['ocean','owwwn'] ret = re.findall('o...n$', 'oceanhelloowwwn') #以n为结尾的匹配,整个字符串的结尾 print(ret) # ['owwwn'] ret = re.findall('abc*', 'abcccc') # 贪婪匹配[0,+∞] print(ret) # ['abcccc'] ret = re.findall('abc+', 'abccc') # [1,+∞] print(ret) # ['abccc'] ret = re.findall('abc?', 'abccc') # [0,1] print(ret) # ['abc'] ret = re.findall('abc{1,4}', 'abccc') print(ret) # ['abccc'] 贪婪匹配
注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配
ret=re.findall('abc*?','abcccccc') print(ret)#['ab']
字符集
# --------------------------------------------字符集[] ret = re.findall('a[bc]d', 'acd') print(ret) # ['acd'] ret = re.findall('[a-z]', 'acd') print(ret) # ['a', 'c', 'd'] ret = re.findall('[.*+]', 'a.cd+') print(ret) # ['.', '+'] # 在字符集里有功能的符号: - ^ \ ret = re.findall('[1-9]', '45dha3') #‘-’在字符集是指范围 print(ret) # ['4', '5', '3'] ret = re.findall('[^ab]', '45bdha3') #^在字符集[]里是‘非’的意思 print(ret) # ['4', '5', 'd', 'h', '3'] ret = re.findall('[\d]', '45bdha3') #\在字符集中是转义,即有意义字符可以转换成普通字符,无意义字符可转化成特殊意义 print(ret) # ['4', '5', '3'] ret = re.findall('\d+','45bda3') print(ret) #['45', '3']
转义字符‘\’ |
反斜杠后边跟元字符去除特殊功能,比如\.
反斜杠后边跟普通字符实现特殊功能,比如\d
\d 匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s 匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
\b 匹配一个特殊字符边界,比如空格 ,&,#等
ret=re.findall('I\b','I am LIST') print(ret)#[] ret=re.findall(r'I\b','I am LIST') print(ret)#['I']
#-----------------------------eg1: import re ret=re.findall('c\l','abc\le') print(ret)#[] ret=re.findall('c\\l','abc\le') print(ret)#[] ret=re.findall('c\\\\l','abc\le') print(ret)#['c\\l'] ret=re.findall(r'c\\l','abc\le') print(ret)#['c\\l'] #-----------------------------eg2: #之所以选择\b是因为\b在ASCII表中是有意义的 m = re.findall('\bblow', 'blow') print(m) m = re.findall(r'\bblow', 'blow') print(m)