云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

「正则表达式」 匹配分组

jxf315 2025-03-13 16:41:28 教程文章 21 ℃



1. 匹配分组相关正则表达式

代码功能|匹配左右任意一个表达式(ab)将括号中字符作为一个分组\num引用分组num匹配到的字符串(?P)分组起别名(?P=name)引用别名为name分组匹配到的字符串

示例1:|

需求:在列表中["apple", "banana", "orange", "pear"],匹配apple和pear

import re

# 水果列表
fruit_list = ["apple", "banana", "orange", "pear"]

# 遍历数据
for value in fruit_list:
    # |    匹配左右任意一个表达式
    match_obj = re.match("apple|pear", value)
    if match_obj:
        print("%s是我想要的" % match_obj.group())
    else:
        print("%s不是我要的" % value)

执行结果:

apple是我想要的
banana不是我要的
orange不是我要的
pear是我想要的

示例2:( )

需求:匹配出163、126、qq等邮箱

import re

match_obj = re.match("[a-zA-Z0-9_]{4,20}@(163|126|qq|sina|yahoo)\.com", "hello@163.com")
if match_obj:
    print(match_obj.group())
    # 获取分组数据
    print(match_obj.group(1))
else:
    print("匹配失败")

执行结果:

hello@163.com
163

需求: 匹配qq:10567这样的数据,提取出来qq文字和qq号码

import re

match_obj = re.match("(qq):([1-9]\d{4,10})", "qq:10567")

if match_obj:
    print(match_obj.group())
    # 分组:默认是1一个分组,多个分组从左到右依次加1
    print(match_obj.group(1))
    # 提取第二个分组数据
    print(match_obj.group(2))
else:
    print("匹配失败")

执行结果:

qq
10567

示例3:\num

需求:匹配出hh

match_obj = re.match("<[a-za-z1-6]+>.*", "hh
") if match_obj: print(match_obj.group()) else: print("匹配失败") match_obj = re.match("<([a-za-z1-6]+)>.*", "hh") if match_obj: print(match_obj.group()) else: print("匹配失败")

运行结果:

hh
hh

需求:匹配出www.baidu.cn

match_obj = re.match("<([a-za-z1-6]+)><([a-za-z1-6]+)>.*", "

www.baidu.cn

") if match_obj: print(match_obj.group()) else: print("匹配失败")

运行结果:

www.itcast.cn

示例4:(?P) (?P=name)

需求:匹配出www.itcast.cn

match_obj = re.match("<(?P[a-zA-Z1-6]+)><(?P[a-zA-Z1-6]+)>.*", "

www.itcast.cn

") if match_obj: print(match_obj.group()) else: print("匹配失败")

运行结果:

www.itcast.cn

猜你喜欢

最近发表
标签列表