正则表达式基础1:常用正则匹配,万能re,re常用语法

常用正则匹配:

  • URL:^https?://[a-zA-Z0-9\.\?=&]*$ (re.S模式,匹配 https://www.baidu.com 类似URL )
  • 常用Email地址:[0-9a-zA-Z_-]+@[0-9a-zA-Z_-]+\.[0-9a-zA-Z_-]+ 或者 [\w-]+@[\w-]+\.[\w-]+
  • 中文字符匹配:[\u4e00-\u9fa5]+ 或者 [^\x00-\xff]+
  • QQ号:[1-9][0-9]{4,} ({4,}表示[0-9]的数字个数不低于4个)
  • ID:^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$

         18|19|([23]\d): 出生年月中年的前两位 18 / 19 / 2x / 3x
         \d{2}:年份后两位
         (0[1-9])|(10|11|12):月份
         ([0-2][1-9])|10|20|30|31:年月日中的日
    

注:身份证号码位数的含意

(1)前1、2位数字表示:所在省份的代码; 
(2)第3、4位数字表示:所在城市的代码; 
(3)第5、6位数字表示:所在区县的代码; 
(4)第7~14位数字表示:出生年、月、日; 
(5)第15、16位数字表示:所在地的派出所的代码; 
(6)第17位数字表示性别:奇数表示男性,偶数表示女性
(7)第18位数字是校检码:也有的说是个人信息码,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示(尾号是10,那么就得用X来代替)。 一般是随计算机的随机产生。

特殊组合([\s\S]*?) == ([.\n]*?) == re.findall(‘.*?‘, re.S)

  • 万能正则表达式 (加‘?’表示懒惰模式,尽可能最小长度匹配; 不加‘?’表示贪婪模式,尽可能最大长度匹配)
  • \s\S : 空白字符+非空白字符,即表示所有字符 all, == ’ .\n ‘(.表示除换行符之外的任意字符,\n表示换行符)
  • re.S: 即DOTAALL 点匹配任意模式,改变.的行为,可以匹配换行符

正则re举例:

import re

# 源格式:strSrc = 'i=d%0A&from=AUTO&to=AUTO&smartresult=dict'
# 目标格式:
#       i:d%0A
#       from:AUTO
#       to:AUTO
#       smartresult:dict

strItems = re.findall('(?<=&)[\w\%=]+|[\w\%=]+(?=&)', strSrc)
#strItems0= re.findall('(.*?)=(.*?)&', strSrc)
print(strItems)     #  list: ['i=d%0A', 'from=AUTO', 'to=AUTO', 'smartresult=dict']
#print(strItems0)    # tuple: [('i', 'd%0A'), ('from', 'AUTO'), ('to', 'AUTO')]  不全
# ['i=d%0A', 'from=AUTO', 'to=AUTO', 'smartresult=dict']

for strItem in strItems:
    strOut = re.sub('=',':', strItem)
    print(strOut)

备注:正则表达式常用语法及说明
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40040404/article/details/81027081