Day12 正则表达式

文章目录

    day12

    1. 正则表达式

    正则表达式(regular expression,常简写为regex、regexp或re),是一种用于匹配和操作文本的强大工具,它是由一系列字符和特殊字符组成的模式,用于描述要匹配的文本模式。正则表达式可以在文本中查找、替换、提取和验证特定的模式。

    2. search()函数

    search()函数 扫描整个字符串 找到第一个匹配的内容 找到就返回匹配对象 没找到返回None 使用场景:只需要判断字符串是否包含某个内容 不介意其在哪个位置

    """
        search()函数  扫描整个字符串  找到第一个匹配的内容
        找到就返回匹配对象 没找到返回None
        使用场景:只需要判断字符串是否包含某个内容 不介意其在哪个位置
    """
    
    import re
    
    text_1 = "111价格99元 库存100件"
    text_2 = "床前明月光"
    result = re.search(r"\d+", text_1)
    if result:
        print("匹配上了",result,type(result),result.group())
    else:
        print("未匹配",result)
    
    
    

    3. match()函数

    match()函数 只从字符串开头开始匹配 开头如果不匹配则直接返回None 不扫描后续的内容

    """
       match()函数  只从字符串开头开始匹配  开头如果不匹配则直接返回None  不扫描后续的内容
    """
    
    import re
    
    text1 = "0123abc"
    text2 = "abc123"
    
    result1 = re.match(r"\d+", text1)
    result2 = re.match(r"\d+", text2)
    
    print(result1.group() if result1 else "未匹配")
    print(result2.group() if result2 else "未匹配")
    
    
    
    
    

    4. findall()函数

    findall()函数 找到字符串中所有匹配的内容 以列表的形式返回所有的结果 如果匹配不到 则返回空列表

    """
        findall()函数  找到字符串中所有匹配的内容
        以列表的形式返回所有的结果 如果匹配不到 则返回空列表
    """
    
    import re
    
    text = "姓名:赵四tony  电话:14589564512  邮箱:abc@163.com  备用:18889567845"
    
    phones = re.findall(r"1[3-9]\d{9}" , text)
    
    print(phones)
    
    letters = re.findall(r"[a-zA-Z]+", text)
    
    print(letters)
    

    5. sub()函数

    sub()函数 替换字符串中匹配的内容 支持批量替换 返回替换后的新字符串 使用场景:敏感词替换 格式清洗 批量修改文字

    """
       sub()函数
       替换字符串中匹配的内容  支持批量替换  返回替换后的新字符串
       使用场景:敏感词替换  格式清洗  批量修改文字
    """
    
    import re
    
    text = "今天天气很不错   垃圾  讨厌  开心"
    
    new_text = re.sub(r"垃圾|讨厌" , "***" , text)
    
    print(new_text)
    
    text2 = "价格100元  重量5KG"
    new_text = re.sub(r"\d+" , "【数字】" , text2)
    print(new_text)
    

    6.split()函数

    split函数 按照指定的规则分割字符串 返回分割后的列表 使用场景:按照复杂的符号分割内容 复杂规则分割文本

    """
        split函数 按照指定的规则分割字符串
        返回分割后的列表
        使用场景:按照复杂的符号分割内容  复杂规则分割文本
    """
    
    import re
    
    text = "苹果,香蕉;橘子 葡萄|西瓜"
    
    result = re.split(r"[,; |]",text)
    print(result)
    
    text = "a132b2c323d4e135"
    
    result = re.split(r"\d+",text)
    
    print(result)
    
    

    7. 匹配手机号

    匹配手机号 match函数是从字符串的开头开始匹配的 所以^写不写效果相同 而 search函数是任何位置匹配都可以 如果不写^ 那么任何位置都能匹配 实际工作中 通常都写^ 和 $ 表示从头匹配到末尾 如果不写这两个则表示任意一段字符串匹配即可

    """
        匹配手机号
        match函数是从字符串的开头开始匹配的 所以^写不写效果相同
        而 search函数是任何位置匹配都可以  如果不写^ 那么任何位置都能匹配
        实际工作中 通常都写^ 和  $ 表示从头匹配到末尾
        如果不写这两个则表示任意一段字符串匹配即可
    """
    
    import re
    
    phones = ["13889562312你好" ,
              "abc15756457878" ,
              "66618956451212" ,
              "你好17365895645" ,
              "16523564578",
              "135235645782",
              ]
    
    pattern = r"^1[3-9]\d{9}$"
    
    for phone in phones:
        print(f"{"合法" if re.match(pattern , phone) else "不合法"}")
    
    
    
    

    8. 匹配邮箱

    """
        匹配邮箱
        \\w
    """
    
    import re
    
    emails = ["你abc@example.com",
              "abc@example.com" ,
              "user.name@subdomain.example.co" ,
              "username@.com",
              "-aabbcc@qq.com"]
    # +-/ 表达为 从+号 到 /号之间的ASCII码 所以 - 要写在最后 才表示 匹配-
    pattern = r"^[a-zA-Z!#$%&'*+/=?^`{|}~.-]+@[\w!#$%&'*+/=?^`{|}~.-]+\.[a-zA-Z]{2,}$"
    
    for email in emails:
        print(f"{"合法" if re.match(pattern , email) else "不合法"} ")
    
    
    
    

    9. 匹配任意单个字符

    """
        匹配任意单个字符
    """
    
    import re
    
    text = "abc 123 _ 中文 漢字 한국어 にほんご"
    
    result  = re.findall(r"\w+", text)
    
    print(result)
    
    

    10. 匹配数字 匹配0~255 的数字

    import re
    
    test = ["0", "9", "50", "100", "199", "200", "255", "256", "-1", "01", "001"]
    
    regex  = r"^([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])$"
    
    for num in test:
        print(f"{"合法" if re.match(regex,num) else "不合法" } ")
    
    

    11. 提取网址

    """
        提取网址
    """
    
    import re
    
    test = """<link rel="alternate" hreflang="zh" href="https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hans" href="https://zh.wikipedia.org/zh-hans/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hans-CN" href="https://zh.wikipedia.org/zh-cn/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hans-MY" href="https://zh.wikipedia.org/zh-my/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hans-SG" href="https://zh.wikipedia.org/zh-sg/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hant" href="https://zh.wikipedia.org/zh-hant/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hant-HK" href="https://zh.wikipedia.org/zh-hk/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hant-MO" href="https://zh.wikipedia.org/zh-mo/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="zh-Hant-TW" href="https://zh.wikipedia.org/zh-tw/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">
    <link rel="alternate" hreflang="x-default" href="https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F">"""
    
    # 提取 href之后的内容 
    # .表示任意单个字符 
    # + 匹配多次
    # ? 等价于 {0,1}
    regex = r'href="(.+?)"'
    
    
    for i in re.findall(regex, test):
        print(i)
    
    

    12. 替换数字为英文

    import re
    
    msg = "i have 2 apples and 3 oranges"
    words = {"1" : "one", "2" : "two", "3" : "three"}
    # 第一个参数 匹配规则 表示会匹配到 单个数字
    # 第二个参数 替换以后的内容
    #       通过lambda表达式 将匹配到的内容传给 x 再根据x调用group函数 从字典中得到对应的 值
    # 第三个参数  处理哪个文本
    new_msg = re.sub(r"\d" ,lambda x : words[x.group()] ,   msg)
    print(new_msg)
    
    

    13. CMS

    """
        客户模块 客户类
            属性:编号 名字 年龄 电话 邮箱
    """
    
    import re
    
    class Customer:
        # 对于注册用户 id是必选项  其他的信息可以后续再选 但是在__str__函数中  如果要格式化 值不能为None
        # 所以 这里 写为字符串类型的 "None"
        def __init__(self, c_id,name = "None", age= "None",phone = "None",email = "None"):
            self.c_id = c_id
            self.name = name
            self.age = age
            self.phone = phone
            self.email = email
    
        @staticmethod
        def check_c_id(c_id):
            # 校验id是否为纯数字格式
            return c_id.isdigit()
    
        @staticmethod
        def check_name(name):
            # 校验名字是否为正常字符
            return name.isalpha()
    
        @staticmethod
        def check_age(age):
            # 校验年龄是否为纯数字格式
            return age.isdigit()
    
        @staticmethod
        def check_phone(phone):
            # bool函数 只要是非0  非"" 非 None  都可以转换为True
            return bool(re.match(r"^1[3-9]\d{9}$",phone))
    
        @staticmethod
        def check_email(email):
            pattern = r"^[\w!#$%&'*+/=?^`{|}~.-]+@[\w!#$%&'*+/=?^`{|}~.-]+\.[a-zA-Z]{2,}$"
            return bool(re.match(pattern,email))
    
        def __str__(self):
            return f"cid:{self.c_id:<10},name:{self.name:<10},age:{self.age:<10},phone:{self.phone:<10},email:{self.email:<10}"
    
    
    
    
    """
        客户管理系统模块
        此模块将实现所有的CRUD操作
    """
    from customer import Customer
    
    
    class CMS:
        def __init__(self):
            # 用户信息字典 k : id   v :客户对象 Customer
            self.customer_dict = {}
    
        def add_customer_id(self):
            customer_id = "None"
            for i in range(3):
                if i < 2:
                    customer_id = input("请输入客户id\n")
                    if Customer.check_c_id(customer_id):
                        break
                    else:
                        print("id必须为纯数字")
                else:
                    customer_id = input("最后一次机会,请输入客户id\n")
                    if Customer.check_c_id(customer_id):
                        break
                    else:
                        print("终止添加用户id")
                        return False
            if customer_id in self.customer_dict:
                print("客户id已存在,不能重复添加")
                return False
            else:
                return customer_id  # 将最终的格式正确的 并且不存在字典中的id 返回
    
        def add_customer_name(self):
            customer_name = "None"
            for i in range(3):
                if i < 2:
                    customer_name = input("请输入客户姓名\n")
                    if Customer.check_name(customer_name):
                        break
                    else:
                        print("名字必须为字符")
                else:
                    customer_name = input("最后一次机会,请输入客户姓名\n")
                    if Customer.check_name(customer_name):
                        break
                    else:
                        print("终止添加客户姓名")
                        return False
            return customer_name
    
        def set_customer_age(self):
            customer_age = input("请输入年龄\n")
            if Customer.check_age(customer_age):
                return customer_age
            else:
                print("暂时不添加年龄也可以")
                return "None"
    
        def set_customer_phone(self):
            customer_phone = input("请输入客户电话\n")
            if Customer.check_phone(customer_phone):
                return customer_phone
            else:
                print("暂时不添加电话也可以")
                return "None"
    
        def set_customer_email(self):
            customer_email = input("请输入邮箱\n")
            if Customer.check_email(customer_email):
                return customer_email
            else:
                print("暂时不添加邮箱也可以")
                return "None"
    
        def add_customer(self):
            if not (customer_id := self.add_customer_id()):
                return
    
            if not (customer_name := self.add_customer_name()):
                return
    
            customer_age = self.set_customer_age()
            customer_phone = self.set_customer_phone()
            customer_email = self.set_customer_email()
    
            customer = Customer(customer_id, customer_name, customer_age, customer_phone, customer_email)
    
            # 存入id为键的字典中
            self.customer_dict[customer_id] = customer
            print(f"添加客户{customer_name}成功!")
    
        def show_all_customer(self):
            if len(self.customer_id_dict) == 0:
                print("暂无客户信息")
            else:
                for i in self.customer_id_dict:
                    print(self.customer_id_dict[i])
    
        def display_menu(self):
            print("""
                ********************客户管理系统*********************
                1.添加客户
                2.删除客户
                3.修改客户
                4.查询客户
                5.显示客户
                6.退出
            """)
    
        def start(self):
            try:
                while True:
                    self.display_menu()
                    choice = input("请输入选项\n")
                    match choice:
                        case "1":
                            self.add_customer()
                        case "2":
                            print("执行删除操作")
                        case "3":
                            print("执行修改操作")
                        case "4":
                            print("执行查询操作")
                        case "5":
                            self.show_all_customer()
                        case "6":
                            print("退出系统")
                            break
                        case _:
                            print("输入错误,请重新输入")
            except (EOFError, KeyboardInterrupt):
                print("退出系统")
    
    
    if __name__ == '__main__':
        cms = CMS()
        cms.start()
    
    
    end