哇嘎嘎,今天高产似那啥,看到了正则表达式,就再来重新巩固一遍啦~~~
因为一些东西我都知道啦,所以就写了一个代码,将所发生的情况都试一试,还是直接上手知识来的更快呀
一些功能必要说明都在注释里
1 import re 2 3 text = ‘Hi, I am Shirley Hilton. I am his wife.‘ 4 text2 = ‘site sea sue sweet see case sse ssee loses‘ 5 text3 = ‘312347829412231877187874328709‘ 6 text4 = ‘aj科 技eu_^%#@^(*&^^-=wio238 jdhfaD按数据库we97r389‘ 7 text5 = ‘(021)88776543 010-55667890 02584453362 0571 66345673 32473 23545346346547900‘ 8 9 print(re.findall(r"\bhi", text)) # \b是表示单词的开头或者结尾,空格、标点、换行都是单词的分隔。 10 print(re.findall("i.", text)) # .代表匹配任意一个字符 11 print(re.findall(".", text)) 12 print(re.findall(r"\S", text)) # 不是空白符的任意一个字符 13 print(re.findall(r"i\S", text)) 14 print(re.findall("I.*e", text)) # *代表前面前面的字符可以重复任意多次(包括0)仅代表数量 15 print(re.findall("I.*?e", text)) # ?懒惰匹配,与*不同,?匹配到最短的就停止 16 print(re.findall(r"\bs\S*?e\b", text2)) # 如果用 r"\bs.*?e\b" 会混进来一个带空格的两个单词,就不是要查询的一个单词了。 17 print(re.findall(r"\bs.*?e\b", text2)) 18 print(re.findall("1[0-9]{10}", text3)) 19 print(re.findall(r"\bc.*l", text2)) 20 print(re.findall(r"\d+", text3)) 21 print(re.findall("[0-9]*", text3)) 22 print(re.findall("[0-9]+", text3)) # +与* 的区别就在于 +是会至少匹配1个, *可以是0 23 print(re.findall(r"\w", text4)) # 匹配字母、数字、下划线、汉字 24 print(re.findall(r"\s", text4)) # 匹配任意的空白符 25 print(re.findall(r"\(0\d{2,3}\)\d{7,8}|0\d{2,3}[ -]?\d{7,8}|\d+", text5)) 26 # 首先看第一个|之前的 \(0\d{2,3}\)是匹配(021) \d{7,8}是后面的88776543 27 # 再看下一个0\d{2,3}[ -]?\d{7,8} 匹配0开头的0xx或者0xxx 然后后面紧跟着空格或者- 这两个符号可以匹配(可有可无?)然后再匹配剩下的后面的数字\d{7,8} 28 # 最后面的\d+ 就是一个收尾的,前面的匹配不成功的就在这里等着了, 根据管道符从左到右依次匹配,所以\d{7,8}放最后啦
执行结果
[‘hi‘] [‘i,‘, ‘ir‘, ‘il‘, ‘is‘, ‘if‘] [‘H‘, ‘i‘, ‘,‘, ‘ ‘, ‘I‘, ‘ ‘, ‘a‘, ‘m‘, ‘ ‘, ‘S‘, ‘h‘, ‘i‘, ‘r‘, ‘l‘, ‘e‘, ‘y‘, ‘ ‘, ‘H‘, ‘i‘, ‘l‘, ‘t‘, ‘o‘, ‘n‘, ‘.‘, ‘ ‘, ‘I‘, ‘ ‘, ‘a‘, ‘m‘, ‘ ‘, ‘h‘, ‘i‘, ‘s‘, ‘ ‘, ‘w‘, ‘i‘, ‘f‘, ‘e‘, ‘.‘] [‘H‘, ‘i‘, ‘,‘, ‘I‘, ‘a‘, ‘m‘, ‘S‘, ‘h‘, ‘i‘, ‘r‘, ‘l‘, ‘e‘, ‘y‘, ‘H‘, ‘i‘, ‘l‘, ‘t‘, ‘o‘, ‘n‘, ‘.‘, ‘I‘, ‘a‘, ‘m‘, ‘h‘, ‘i‘, ‘s‘, ‘w‘, ‘i‘, ‘f‘, ‘e‘, ‘.‘] [‘i,‘, ‘ir‘, ‘il‘, ‘is‘, ‘if‘] [‘I am Shirley Hilton. I am his wife‘] [‘I am Shirle‘, ‘I am his wife‘] [‘site‘, ‘sue‘, ‘see‘, ‘sse‘, ‘ssee‘] [‘site‘, ‘sea sue‘, ‘sweet see‘, ‘sse‘, ‘ssee‘] [‘12347829412‘, ‘18771878743‘] [‘case sse ssee l‘] [‘312347829412231877187874328709‘] [‘312347829412231877187874328709‘, ‘‘] [‘312347829412231877187874328709‘] [‘a‘, ‘j‘, ‘科‘, ‘技‘, ‘e‘, ‘u‘, ‘_‘, ‘w‘, ‘i‘, ‘o‘, ‘2‘, ‘3‘, ‘8‘, ‘j‘, ‘d‘, ‘h‘, ‘f‘, ‘a‘, ‘D‘, ‘按‘, ‘数‘, ‘据‘, ‘库‘, ‘w‘, ‘e‘, ‘9‘, ‘7‘, ‘r‘, ‘3‘, ‘8‘, ‘9‘] [‘ ‘, ‘ ‘] [‘(021)88776543‘, ‘010-55667890‘, ‘02584453362‘, ‘0571 66345673‘, ‘32473‘, ‘23545346346547900‘]
其他一些没有说明的 吱
^ - 匹配字符串的开始
$ - 匹配字符串的结束
\S其实就是\s的反义,任意不是空白符的字符。同理,还有:
\W - 匹配任意不是字母,数字,下划线,汉字的字符
\D - 匹配任意非数字的字符
\B - 匹配不是单词开头或结束的位置
? - 重复零次或一次
{n,} - 重复n次或更多次
{n,m} - 重复n到m次
[a]的反义是[^a],表示除a以外的任意字符。[^abcd]就是除abcd以外的任意字符。
原文:https://www.cnblogs.com/dummersoul/p/12176627.html