博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python使用正则表达式

Posted on 2023-08-07 18:43  steve.z  阅读(17)  评论(0编辑  收藏  举报

Python 使用正则表达式

#
#   py_regex.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/7 17:18.
#

# 1. Python 使用正则表达式, 需要导入的模块 re 模块
# 2. 正则表达式基本方法:
# - match()
# - search()
# - findall()

import re


def test_re():
    s = "hello python, welcome to python China!!! python"

    # 1. match()
    result = re.match("python", s)
    print(result)

    # 2. search()
    r1 = re.search("python", s)
    print(r1)

    # 3. findall()
    r2 = re.findall("python", s)
    print(r2)


def re_demo():
    # 1. 匹配只能由字母和数字组成,长度为 6-10位
    while True:
        s = input("请输入只能由字母和数字组成,长度为 6-10位")
        r = re.findall("^[a-zA-Z0-9]{6,10}$", s)
        print(r)


def re_demo2():
    # 2. 匹配纯数字,第1位不能是0,长度限制:5-11
    while True:
        s = input("匹配纯数字,第1位不能是0,长度限制:5-11")
        r = re.findall("^[1-9][0-9]{4,10}$", s)
        print(r)


def re_demo3():
    while True:
        # 3. 匹配邮箱地址. 只允许 qq、163、gmail
        s = input("匹配邮箱地址. 只允许 qq、163、gmail:")
        r = re.findall(r"(^[\w-]+(\.[\w-]+)*@(qq|163|gmail)\.[a-zA-Z]+$)", s)
        print(r)


if __name__ == "__main__":
    # re_demo()
    # re_demo2()
    re_demo3()