1、正则表达式(二)
"""
元字符(二)
1、匹配任意(非)数字字符 \d:匹配任意数字字符 \D:匹配任意非数字字符
2、匹配任意(非)普通字符 \w:匹配任意普通字符 \W:匹配任意非普通字符
普通字符:数字、字母、下划线、汉字
3、匹配任意(非)空字符 \s:匹配空字符 \S:匹配任意非空字符
空字符: 空格 \r \n \t \v \f
4、匹配开头结尾位置 元字符:\A表示开头 \Z表示结尾
5、匹配(非)单词边界位置 \b:表示单词边界 \B:表示非单词边界
单词边界:数字字母(汉字)下划线与其他字符的交界位置
"""
import re
# 案例1:匹配端口
print(re.findall('\d{1,9}', "Mysql:3306,Port:80")) # ['3306', '80']
print(re.findall('\D{1,9}', "Mysql:3306,Port:80")) # ['Mysql:', ',Port:']
# 案例2:
print(re.findall('\w+', "Student stu = Student()")) # ['Student', 'stu', 'Student']
print(re.findall('\W+', "Student stu = Student()")) # [' ', ' = ', '()']
# 案例3:
print(re.findall('\w+\s+\w+', "Hello world")) # ['Hello world']
print(re.findall('\S+', "Hello world")) # ['Hello', 'world']
# 案例4:
print(re.findall('world', "hello world")) # ['world']
print(re.findall('\Aworld', "hello world")) # []
print(re.findall('world\Z', "hello world")) # ['world']
# 案例5:
print(re.findall('\Wis\W', "This is a test")) # [' is ']
# 注意!!!! 使用\b时,需使用r将其转换为原始字符串
print(re.findall(r'\bis\b', "This is a test")) # ['is'] 此时匹配的第二个
print(re.findall(r'\Bis\b', "This is a test")) # ['is'] 此时匹配的第一个
2、总结
类别 | 元字符 |
---|---|
匹配字符 | \W、 \w 、\D 、\d、 \S 、\s、 . […]、 [^ …] |
匹配重复 | *、+ 、? 、 {n} 、 {m,n} |
匹配为止 | ^、$、\b、\B、\A、\Z |
其他 | \、()、| |
3、正则表达式的转义
如果使用正则表达式匹配特殊字符,需要使用\表示转义
特殊字符:. * + ?^ $ [] () {} | \
# 案例1:
print(re.findall('\d+\.\d+', "23,343,56.34,23.1"))
# ['56.34', '23.1']
print(re.findall('\d\*{2}\d+', "2**16"))
# ['2**16']
注意:\b可以在Python字符串中转义,所以需要加r【不会进行字符串的转义解析】或者使用\将\转义
print(re.findall(r'\bis\b',"This is a test"))
print(re.findall('\\bis\\b',"This is a test"))