网站首页 > java教程 正文
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]+>.*</[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>
需求:匹配出www.baidu.cn
match_obj = re.match("<([a-zA-Z1-6]+)><([a-zA-Z1-6]+)>.*</\\2></\\1>", "<html><h1>www.baidu.cn</h1></html>")
if match_obj:
print(match_obj.group())
else:
print("匹配失败")
运行结果:
<html><h1>www.itcast.cn</h1></html>
示例4:(?P) (?P=name)
需求:匹配出www.itcast.cn
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>
猜你喜欢
- 2024-11-16 String.replaceAll方法,正则妙用
- 2024-11-16 348.C# 中的正则表达式断言:精确匹配的秘诀
- 2024-11-16 《MySQL 入门教程》第 09 篇 字符串模式匹配
- 2024-11-16 mysql正则匹配中文时存在的问题(mysql 正则匹配)
- 2024-11-16 技术趣讲 | 60 分钟搞懂「正则表达式」
- 2024-11-16 PHP 正则表达式匹配中文问题(php正则表达式匹配字符串)
- 2024-11-16 JZ-052-正则表达式匹配(正则表达式 匹配?)
- 2024-11-16 Nginx Location深入了解匹配优先级的秘密#java面试
- 2024-11-16 PHP正则表达式核心技术完全详解 第7节 数组元素正则匹配
- 2024-11-16 你知道python正则表达式如何跨行匹配吗?
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- java反编译工具 (77)
- java反射 (57)
- java接口 (61)
- java随机数 (63)
- java7下载 (59)
- java数据结构 (61)
- java 三目运算符 (65)
- java对象转map (63)
- Java继承 (69)
- java字符串替换 (60)
- 快速排序java (59)
- java并发编程 (58)
- java api文档 (60)
- centos安装java (57)
- java调用webservice接口 (61)
- java深拷贝 (61)
- 工厂模式java (59)
- java代理模式 (59)
- java.lang (57)
- java连接mysql数据库 (67)
- java重载 (68)
- java 循环语句 (66)
- java反序列化 (58)
- java时间函数 (60)
- java是值传递还是引用传递 (62)
本文暂时没有评论,来添加一个吧(●'◡'●)