正则表达式练习题

"""
***************************
@Project :正则

@Author :majun
@Date : 2020/10/29 10:41

*******************************
"""
import re

#1.匹配 aaa.aaa.aaa.aaa, 其中a为任意字母
def Aaa():
    string='aaa.aaa.aaa.aaa'
    r=r'[a-zA-Z]{3}.[a-zA-Z]{3}.[a-zA-Z]{3}.[a-zA-Z]{3}'
    match=re.findall(r,string)
    print (match)

#2.判断身份证号码,包括18位和15位的情况
def Sfc():
    sfz_18=r'^[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]$'
    sfz_15=r'([1-9]\d{5}\d{2}(?:(?:0[1-9])|(?:10|11|12))(?:(?:[0-2][1-9])|10|20|30|31)\d{3})'
    ID_18='350702199812220810'
    ID_15='310112850409522'
    match_18=re.match(sfz_18,ID_18).group()
    match_15=re.match(sfz_15,ID_15).group()
    print (match_18)
    print (match_15)


#3. 判断是否符合 USD 格式   格式如 $1,123,343.12
def Usd():
    dollar='$1,123,343.12'
    US_dollar = r'^\$[1-9]\d{0,2}((,\d{3})|0)*(.\d{2})$'
    match=re.match(US_dollar,dollar).group()
    print(match)

# 4.单词匹配
# his history hisense his are  找出所有his的单词
# hised historyed hisenseed his aedre  找出所有后缀带ed的单词
def Words():
    string_1 = 'his history hisense his are'
    string_2 = 'hised historyed hisenseed his aedre'
    r_1 = r'\bhis\b'
    r_2 = r'[a-zA-Z]*ed\b'
    print(re.findall(r_1, string_1))
    print(re.findall(r_2, string_2))
#2.info = """This is the first line.
#Hi this is the second line.
#This is the third line."""
    #    匹配所有 This is the xxx line(不区分大小写)
#    只匹配行首为This is the xxx line(不区分大小写)

def String():
    info = """This is the first line.
    Hi this is the second line.
    This is the third line."""
    print(re.findall(r'this.*?line', info,re.I))
    print(re.findall(r'^this.*?line', info,re.I))
    # 3.思考单行模式和多行模式是否可以同时使用,如果可以将第2题同时使用单行模式和多行模式来匹配。
    print(re.findall(r'this.*?line', info, re.M|re.I|re.S))

if __name__=='__main__':
    Aaa()
    Sfc()
    Usd()
    Words()
    String()

 

posted @ 2020-11-02 09:17  Mangnolia  阅读(203)  评论(0编辑  收藏  举报