Python进阶之正则表达式
Python进阶之正则表达式
何平安text=”asdjasdj124lashasl324hoasgfqwfps45j4543466fhjkhs7897dkhfspfsdfjls67576593d”
- 找出字符串中所有数字
1 | re.findall(r"\d",text) |
输出: [‘1’, ‘2’, ‘4’, ‘3’, ‘2’, ‘4’, ‘4’, ‘5’, ‘4’, ‘5’, ‘4’, ‘3’, ‘4’, ‘6’, ‘6’, ‘7’, ‘8’, ‘9’, ‘7’, ‘6’, ‘7’, ‘5’, ‘7’, ‘6’, ‘5’, ‘9’, ‘3’]
- 找出字符串所有连续数字
1 | re.findall(r"\d+",text) |
输出:[‘124’, ‘324’, ‘45’, ‘4543466’, ‘7897’, ‘67576593’]
- 找出所有单个字符
1 | print(re.findall(r"\w",text)) |
输出:[‘a’, ‘s’, ‘d’, ‘j’, ‘a’, ‘s’, ‘d’, ‘j’, ‘1’, ‘2’, ‘4’, ‘l’, ‘a’, ‘s’, ‘h’, ‘a’, ‘s’, ‘l’, ‘3’, ‘2’, ‘4’, ‘h’, ‘o’, ‘a’, ‘s’, ‘g’, ‘f’, ‘q’, ‘w’, ‘f’, ‘p’, ‘s’, ‘4’, ‘5’, ‘j’, ‘4’, ‘5’, ‘4’, ‘3’, ‘4’, ‘6’, ‘6’, ‘f’, ‘h’, ‘j’, ‘k’, ‘h’, ‘s’, ‘7’, ‘8’, ‘9’, ‘7’, ‘d’, ‘k’, ‘h’, ‘f’, ‘s’, ‘p’, ‘f’, ‘s’, ‘d’, ‘f’, ‘j’, ‘l’, ‘s’, ‘6’, ‘7’, ‘5’, ‘7’, ‘6’, ‘5’, ‘9’, ‘3’, ‘d’]
- 找出长度为n-m的数字
1 | print(re.findall(r"\d{1,3}",text)) |
输出:[‘124’, ‘324’, ‘45’, ‘454’, ‘346’, ‘6’, ‘789’, ‘7’, ‘675’, ‘765’, ‘93’]
text2=”电话1:023-234723947,电话2:0234-823957223,电话3:19812876402,电话3:0642-98346,电话4:21387645609”
- 找出指定长度和形状的字符串
1 | print(re.findall(r"\d{3,4}-\d{7,8}|1\d{10}",text2)) |
输出:[‘023-23472394’, ‘0234-82395722’, ‘19812876402’]
这句意思是找出-前面数字长度为3-4且-后面为数字长度为7-8的和1开头且后面位数为10的。“|”这个是“和”的意思
text3=”barbar carcar harhel”
- 找出字符串中相同的字段并以列表元组返回
1 | print(re.findall(r"(\w{3})(\1)",text3)) |
输出:[(‘bar’, ‘bar’), (‘car’, ‘car’)]