python正则表达式

 

正则表达式是一种通用的字符串匹配技术,是不会因为编程语言不一样而发生变化的,想要查找某种特征的,具有一定规则的字符串,都可以尝试使用正则表达式

1.  [abc]  匹配中括号中的任意一个字符   [0-3] 匹配0,1,2,3中的任意一个字符    [a-z]匹配所有的小写字母
re_pattern = r'[abc]'
res = re.findall(re_pattern, "abcwofowpqfowdhfkjdsjhfa")
print(res) ----> ['a', 'b', 'c', 'a']


2. . 匹配任意的一个字符串 除了\n

re_pattern = r'[abc]'
res = re.findall(re_pattern, "abcwofowpqfowdhfkjdsjhfa")
print(res) ----> ['a', 'b', 'c', 'w', 'o', 'f', 'o', 'w', 'p', 'q', 'f', 'o', 'w', 'd', 'h', 'f', 'k', 'j', 'd', 's', 'j', 'h', 'f', 'a']

3. {m}匹配任意多个
4.   \d  匹配任意一个数字   等价于 [0-9]
5. \D 匹配任意一个非数字 等价于[^0-9]

6. \w 匹配字母数字下划线 等价于[a-zA-Z0-9_]
7. \W 匹配非字母数字下划线 等价于[^a-zA-Z0-9_]


8. \w{2} 匹配俩个\w(匹配花括号当中的数字次)

re_pattern = r'\w{2}'
res = re.findall(re_pattern, "1—we@dj")
print(res) ----> ['we', 'dj']

9. {2,} 匹配至少2次,尽可能的匹配多次

10. {,2} 匹配最多2次,包括0次,
re_pattern = r'\w{,2}'
res = re.findall(re_pattern, "1—we1@dj")
print(res) ---> ['1', '', 'we', '1', '', 'dj', ''] 最后为空原因,最后面没有了就是匹配0次,所以有个空

11. {2,4} 匹配2-4次,贪婪模式下,尽可能多的匹配

12. 匹配手机号码
re_pattern = r'1[35789]\d{9}'
res = re.findall(re_pattern, "123wqwe2343_13331331111232")
print(res) ---> ['13331331111']


13. * 匹配任意字符0次或者任意次
re_pattern = r'\d*'
res = re.findall(re_pattern, "123wqwe2343_13331331111232")
print(res) --->['123', '', '', '', '', '2343', '', '13331331111232', '']

14. + 匹配一次或者任意次
re_pattern = r'\d+'
res = re.findall(re_pattern, "123wqwe2343_13331331111232")
print(res) ---> ['123', '2343', '13331331111232']

15 . \d. 匹配数字和任意字符

16. ? 匹配0次或者1次(非贪婪模式,尽量少的匹配)

17. ^ 匹配开头, $ 匹配结尾

 

posted @ 2020-04-25 21:32  学编程的狗狗  阅读(89)  评论(1)    收藏  举报