Loading

正则表达式

  • 用正则表达式查找文本模式
import re

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d\-\d\d\d\d')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print(mo.group())

用import re 导入正则表达式模块;

用re.compile()函数创建一个Regex对象;

向Regex对象的search()方法传入想查找的字符串。它返回一个Match对象;

调用Match对象的group()方法,返回实际匹配文本的字符串。

  • 用正则表达式匹配更多模式
    • 利用括号分组
复制代码
phoneNumReg = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo1 = phoneNumReg.search('My number is 415-555-4222.')
print(mo1.group(1))
print(mo1.group(2))
print(mo1.group(0))
print(mo1.groups())

415
555-4222
415-555-4222
('415', '555-4222')
复制代码
    • 用管道匹配多个分组
heroRegex = re.compile(r'Batman|Tina Fey')
mo1 = heroRegex.search("Batman and Tina Fey.")
print(mo1.group())

batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
mo = batRegex.search("Batmobile lost a wheel")
print(mo.group())
print(mo.group(1))
    • 用问号实现可选匹配
复制代码
# 用问号实现可选匹配(匹配这个问号之前的分组零次或一次)
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search("The Adventures of Batman")
print(mo1.group())

mo2 = batRegex.search("The Adventures of Batwoman")
print(mo2.group())

phoneRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
mo1 = phoneRegex.search("My number is 415-555-4242")
print(mo1.group())
mo2 = phoneRegex.search("My number is 555-4242")
print(mo2.group())
复制代码
    • 用星号匹配0次或多次
复制代码
batRegex = re.compile(r"Bat(wo)*man")
mo1 = batRegex.search("The Adventures of Batman")
print(mo1.group())

mo2 = batRegex.search("The Adventures of Batwoman")
print(mo2.group())

mo3 = batRegex.search("The Adventures of Batwowowowoman")
print(mo3.group())
复制代码
    • 用加号匹配一次或多次
复制代码
batRegex = re.compile(r"Bat(wo)+man")
mo1 = batRegex.search("The Adventures of Batwoman")
print(mo1.group())

mo2 = batRegex.search("The Adventures of Batwowowowoman")
print(mo2.group())

mo3 = batRegex.search("The Adventures of Batman")
print(mo3==None)
复制代码
    • 用花括号匹配特定次数
haRegex = re.compile(r'(Ha){3}')
mo1 = haRegex.search("HaHaHa")
print(mo1.group())

mo2 = haRegex.search("Ha")
print(mo2==None)

 

作者:solomon-zj

出处:https://www.cnblogs.com/solomon-zj/p/17382728.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   solomon-zj  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示