匹配分组

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

代码功能
|匹配左右任意一个表达式
(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 的匹配方法

需求:匹配出<html>hh</html>

match_obj = re.match("<[a-zA-Z1-6]+>.*</[a-zA-Z1-6]+>", "<html>hh</div>")

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

match_obj = re.match("<([a-zA-Z1-6]+)>.*</\\1>", "<html>hh</html>")

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

运行结果:
<html>hh</div>
<html>hh</html>

需求:匹配出<html><h1>www.itcast.cn</h1></html>

match_obj = re.match("<([a-zA-Z1-6]+)><([a-zA-Z1-6]+)>.*</\\2></\\1>", "<html><h1>www.itcast.cn</h1></html>")

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

运行结果:
<html><h1>www.itcast.cn</h1></html>

4.演示 (?P<name>) (?P=name) 的匹配方法

需求:匹配出<html><h1>www.itcast.cn</h1></html>

match_obj = re.match("<(?P<name1>[a-zA-Z1-6]+)><(?P<name2>[a-zA-Z1-6]+)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>")

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

运行结果:
<html><h1>www.itcast.cn</h1></html>

二.匹配分组相关正则表达式的总结

  • | 表示匹配左右任意一个表达式
  • (ab) 表示将括号中字符作为一个分组
  • \num 表示引用分组num匹配到的字符串
  • (?P<name>) 表示分组起别名
  • (?P=name) 表示引用别名为name分组匹配到的字符串
  • (分组数据):分组数是从左到右的方式进行分配的,最左边的是第一个分组,依次类推
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值