正则表达式

正则表达式

正则表达式主要用于数据的查找与筛选,在爬虫、运维等技术常常运用

导入

需求:编写代码校验用户输入的手机号是否合法:常见 13 15 17 18 19开头
1.python代码逻辑实现
phone_num = input("请输入你的电话号码:>>>").strip()
if phone_num.isdigit():
    if len(phone_num)==11:
        if phone_num.startswith('13') or phone_num.startswith('15') or phone_num.startswith('17') or phone_num.startswith('18') or phone_num.startswith('19'):
            phone_num = int(phone_num)
            print("输入的手机号合法")
        else:
            print("开头数字错误")
    else:
        print("电话号码十一位哦")
else:
    print("只能是纯数字哦")
    
2.正则表达式实现
import re
phone_num = input("请输入你的电话号码:>>>").strip()
if re.match('^(13|15|17|18|19)[0-9]{9}',phone_num):
    print("输入正确")
else:
    print("没输入对哦")
ps:正则表达式本质上是使用一些符号的组合产生一些特殊的含义,然后去字符串中筛选出符合条件的数据
   正则表达式线上测试网址:http://tool.chinaz.com/regex/

正则表达式之字符组

字符组在没有量词修饰的情况下,一次只会针对一个数据值;在中括号编写的多个数据值彼此都是或的关系

字符组说明
[0-9]匹配0-9之间任意的数字[0123456789]
[A-Z]匹配大写字母A-Z的任意字母
[a-z]匹配小写字母a-z的任意字母
[0-9a-zA-Z]匹配数字、小写字母、大写字母都可以

正则表达式之特殊符号

特殊符号在没有量词修饰的情况下,一个符号一次只会针对一个数据值

特殊符号说明
.匹配出换行符(\n)以外的任意字符
\w匹配字母或数字或下划线
\W匹配非字母或数字或下划线
\d匹配数字
^匹配字符串的开头
$匹配字符串的结尾
a|b匹配字符a或b
()给正则表达式分组,不影响正则表达式的匹配(用于给后续的正则起别名,分组获取对应数据)
[]匹配字符组中的字符
[^]匹配除了字符组中字符的所有字符

正则表达式之量词

在正则表达式中多有的量词默认都是贪婪匹配(尽可能多的获取),且量词不能单独使用,必须跟在表达式的后面,并且只能影响紧挨着的左边哪一个

量词说明
*重复零次或更多次(默认就是尽可能的多)
+重复一次或更多次(默认就是尽可能的多)
重复零次或一次(默认就是一次)
{n}重复n次
{n,}重复n次或更多次
{n,m}重复n到m次

正则表达式练习题

量词练习
正则待匹配字符结果
李.?李杰和李莲英和李二棍子李杰 李莲 李二
李.*李杰和李莲英和李二棍子李杰和李莲英和李二棍子
李.+李杰和李莲英和李二棍子李杰和李莲英和李二棍子
李.{1,2}李杰和李莲英和李二棍子李杰和 李莲英 李二棍
李.*?李杰和李莲英和李二棍子李 李 李
字符集练习
正则带匹配字符结果
李[杰莲英二棍子]*李杰和李莲英和李二棍子李杰 李莲英 李二棍子
李 [^和]*李杰和李莲英和李二棍子李杰 李莲英李二棍子
[\d]456bdha34 5 6 3
[\d]+456bdha3456 3

贪婪匹配与非贪婪匹配

所有的量词默认就是贪婪匹配,但是如果在量词的后面紧跟一个问号,就变成非贪婪匹配;

待匹配的文本:<script>alert(123)</script>
1.贪婪匹配
正则表达式:<.*>
结果:<script>alert(123)</script>

2.非贪婪匹配
正则表达式:<.*?>
结果:<script>  </script>

ps:以后我们在使用贪婪匹配或者非贪婪匹配的时候一般都是用.*或者.*?,并且结束的标志有上述符号左右两边添加的表达式决定

取消转义

1.正则表达式:在斜杠前面加斜杠
    待匹配字符:\n	正则:\\n	结果:\n
    待匹配字符:\\n	正则:\\\\n  结果:\\n
2.python:在字符串前面加r
    r'\n'
    r'\\n'

正则表达式实战

常见的正则百度查找,在理解的基础上修改即可

1.校验用户手机号的正则:0?(13|14|15|17|18|19)[0-9]{9}
2.校验用户身份证的正则:\d{17}[\d|x]|\d{15}
3.校验用户邮箱的正则:\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}
4.校验用户qq号的正则:[1-9]([0-9]{5,11})

作业

项目功能:用户注册、用户登录、添加购物车、结算购物车、查看购物车、编辑购物车

import os
import json

base_dir = os.path.dirname(__file__)
db_dir_path = os.path.join(base_dir, 'db')
if not os.path.exists(db_dir_path):
    os.mkdir(db_dir_path)

tag_dic = {
    'username': None
}


def outer(func_name):
    def inner(*args, **kwargs):
        if tag_dic['username']:
            res = func_name(*args, **kwargs)
            return res
        else:
            print("请先登录")
            login()

    return inner


def register():
    while True:
        user_name = input("请输入你想注册的用户名>>>:").strip()
        user_pwd = input("请输入你的用户名密码>>>:").strip()
        confirm_pwd = input("请在输入一次密码>>>:").strip()
        if user_pwd != confirm_pwd:
            print("两次输入的密码不一致")
            continue
        user_file = os.path.join(db_dir_path, '%s.json' % user_name)
        if os.path.isfile(user_file):
            print("该用户名已经存在,重新换一个用户名吧")
            continue
        user_dic = {'name': user_name, 'pwd': user_pwd, 'balance': 15000, 'shop_car': {}}
        with open(user_file, 'w', encoding='utf8')as f:
            json.dump(user_dic, f)
            print(f"用户{user_name}添加成功")
            break


def login():
    while True:
        user_name = input("请输入你的用户名>>>:").strip()
        user_pwd = input("请输入你的密码>>>:").strip()
        user_file = os.path.join(db_dir_path, "%s.json" % user_name)
        if not os.path.isfile(user_file):
            print("用户名不存在,请重新登陆")
            continue
        with open(user_file, 'r', encoding='utf8') as f:
            user_dic = json.load(f)
        if user_dic['pwd'] == user_pwd:
            print(f"用户{user_name}登陆成功")
            tag_dic['username'] = user_name
            break
        else:
            print("用户名或密码错误,请重新登陆")


@outer
def add_shop_car():
    good_list = [
        ['挂壁面', 3],
        ['印度飞饼', 22],
        ['极品木瓜', 666],
        ['土耳其土豆', 999],
        ['伊拉克拌面', 1000],
        ['董卓戏张飞公仔', 2000],
        ['仿真玩偶', 10000]
    ]
    new_dic = {}
    while True:
        print("============================================")
        for i, j in enumerate(good_list, 1):  # 1 ['挂壁面', 3]
            print(f"商品编号:{i}    商品名称:{j[0]}    商品价格:{j[1]}")
        print("============================================")
        choice_id = input("请输入你想加入购物车商品对应的编号(q)>>>:").strip()
        if choice_id == 'q':
            user_file = os.path.join(db_dir_path, "%s.json" % tag_dic.get('username'))
            with open(user_file, 'r', encoding='utf8')as f:
                user_dic = json.load(f)
            old_dic = user_dic.get('shop_car')  # {}
            for i in new_dic:
                if i in old_dic:
                    old_dic[i][0] += new_dic[i][0]
                else:
                    old_dic[i] = new_dic[i]
            user_dic['shop_car'] = old_dic
            with open(user_file, 'w', encoding='utf8')as f1:
                json.dump(user_dic, f1, ensure_ascii=False)
                print("添加成功")
                break
        if not choice_id.isdigit():
            print("请输入数字")
            continue
        choice_id = int(choice_id)
        if choice_id not in range(1, len(good_list) + 1):
            print("你输入的编号超出范围了")
            continue
        goods_name = good_list[choice_id - 1][0]
        goods_price = good_list[choice_id - 1][1]
        goods_num = input("请输入你想添加的数量:>>>").strip()
        if not goods_num.isdigit():
            print("只能输入数字哦")
            continue
        goods_num = int(goods_num)
        if goods_name not in new_dic:
            new_dic[goods_name] = [goods_num, goods_price]  # {'极品木瓜':[个数,单价]}

        else:
            new_dic[goods_name][0] += goods_num


@outer
def account_shop_car():
    user_file = os.path.join(db_dir_path, "%s.json" % tag_dic.get('username'))
    with open(user_file, 'r', encoding='utf8')as f:
        user_dic = json.load(f)
    shop_car_goods= user_dic.get("shop_car")  # {'挂壁面': [914, 3], '印度飞饼': [38, 22], '极品木瓜': [39, 666], '土耳其土豆': [56, 999]}
    goods_sum = 0
    for item in shop_car_goods.values():  # [914, 3]
        price = item[0] * item[1]
        goods_sum += price
    if user_dic['balance']>= goods_sum:
        user_dic['balance'] -= goods_sum
        user_dic['shop_car'] = {}
        print(f"总价格为{goods_sum},剩余{user_dic['balance']}")
        with open(user_file, 'w', encoding='utf8')as f:
            json.dump(user_dic,f,ensure_ascii=False)
    else:
        print("余额不够")



@outer
def check_shop_car():
    user_file = os.path.join(db_dir_path, "%s.json" % tag_dic.get('username'))
    with open(user_file, 'r', encoding='utf8')as f:
        user_dic = json.load(f)
        goods_info = user_dic.get('shop_car') # {'挂壁面': [914, 3], '印度飞饼': [38, 22], '极品木瓜': [39, 666], '土耳其土豆': [56, 999]}
    print("============================================")
    for i in goods_info.items():  # ('挂壁面', [914, 3])
        print(f"商品名称:{i[0]}    商品数量:{i[1][0]}   商品价格:{i[1][1]}")
    print("============================================")
@outer
def edit_shop_car():
    user_file = os.path.join(db_dir_path, "%s.json" % tag_dic.get('username'))
    while True:
        with open(user_file, 'r', encoding='utf8')as f:
            user_dic = json.load(f)
            goods_info = user_dic.get('shop_car') # {'挂壁面': [914, 3], '印度飞饼': [38, 22], '极品木瓜': [39, 666], '土耳其土豆': [56, 999]}
        goods_list = []
        for i in goods_info:
            goods_list.append(i)
        print("============================================")
        for i,j in enumerate(goods_list,1):
            print(f"商品编号:{i}  商品名称:{j}")
        print("============================================")
        choice_id = input("请输入你想要修改商品名称的编号:>>>").strip()
        if not choice_id.isdigit():
            print("输入数字")
            continue
        choice_id = int(choice_id)
        if  choice_id not in range(1,len(goods_list)+1):
            print("超出了范围")
            continue

        goods_name = goods_list[choice_id - 1]
        choice_type = input("""请输入你想要修改的类型:
                            1.删除对应的商品
                            2.修改商品的数量
                            >>>:""").strip()
        if choice_type == '1':
            goods_info.pop(goods_name)
        elif choice_type =='2':
            choice_num = input("请输入你想修改的数量>>>:").strip()
            if not choice_num.isdigit():
                print("请输入数字")
                continue
            choice_num = int(choice_num)
            goods_info[goods_name][0] = choice_num
        else:
            print("输入不合法")
        user_dic['shop_car'] = goods_info
        with open(user_file, 'w', encoding='utf8')as f1:
            json.dump(user_dic,f1)
            break


dic_func = {
    '1': register,
    '2': login,
    '3': add_shop_car,
    '4': account_shop_car,
    '5': check_shop_car,
    '6': edit_shop_car
}
while True:
    print("""
    *****************************************
    1.用户注册
	2.用户登录
	3.添加购物车
	4.结算购物车
	5.查看购物车
	6.修改购物车
    *****************************************
   """)
    choice = input("请输入你想要的功能的序号:>>>").strip()
    if choice in dic_func:
        dic_func.get(choice)()
    else:
        print("输入的编号不正确")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值