python——正则表达式(正则对象)

简介: python——正则表达式(正则对象)

正则对象

来看一下正则表达式对象的相应方法。


Pattern.search(string[, pos[, endpos]])

扫描整个 string 寻找第一个匹配的位置,并返回一个相应的匹配对象,如果没有匹配,就返回 None;可选参数 pos 给出了字符串中开始搜索的位置索引,默认为 0;可选参数 endpos 限定了字符串搜索的结束。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
print(pattern.search('aBcdef'))
print(pattern.search('aBcdef', 1, 3))

Pattern.match(string[, pos[, endpos]])

如果 string 的开始位置能够找到这个正则样式的任意个匹配,就返回一个相应的匹配对象,如果不匹配,就返回 None。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
print(pattern.match('aBcdef'))
print(pattern.match('aBcdef', 1, 3))

Pattern.fullmatch(string[, pos[, endpos]])

如果整个 string 匹配这个正则表达式,就返回一个相应的匹配对象,否则就返回 None。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
print(pattern.match('aBcdef'))
print(pattern.match('aBcdef', 1, 3))

Pattern.fullmatch(string[, pos[, endpos]])

如果整个 string 匹配这个正则表达式,就返回一个相应的匹配对象,否则就返回 None。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
print(pattern.fullmatch('Bc'))
print(pattern.fullmatch('aBcdef', 1, 3))

Pattern.split(string, maxsplit=0)

等价于 re.split() 函数,使用了编译后的样式。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
print(pattern.split('abc, aBcd, abcde.'))

Pattern.findall(string[, pos[, endpos]])

使用了编译后样式,可以接收可选参数 pos 和 endpos,限制搜索范围。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
print(pattern.findall('abcefabCdeABC'))
print(pattern.findall('abcefabCdeABC', 0, 6))

Pattern.finditer(string[, pos[, endpos]])

使用了编译后样式,可以接收可选参数 pos 和 endpos ,限制搜索范围。看一下示例:

import re
pattern = re.compile(r'bc', re.I)
it = pattern.finditer('12bc34BC56', 0, 6)
for match in it:
    print(match)

Pattern.sub(repl, string, count=0)

使用了编译后的样式。看一下示例:

import re
pattern = re.compile(r'#.*$')
str = 'ityard # 是我的名字'
print(pattern.sub('', str))

Pattern.subn(repl, string, count=0)

使用了编译后的样式。看一下示例:

import re
pattern = re.compile(r'#.*$')
str = 'ityard # 是我的名字'
print(pattern.subn('', str))


相关文章
|
26天前
|
机器学习/深度学习 前端开发 Windows
【夯实技术基本功】「底层技术原理体系」全方位带你认识和透彻领悟正则表达式(Regular Expression)的开发手册(正则符号深入解析 )
【夯实技术基本功】「底层技术原理体系」全方位带你认识和透彻领悟正则表达式(Regular Expression)的开发手册(正则符号深入解析 )
31 0
|
1月前
|
存储 安全 UED
一文让你读懂Python中的Response对象
一文让你读懂Python中的Response对象
41 0
|
8天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
48 0
|
9天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
30天前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
1月前
|
Python
请解释Python中的正则表达式以及如何使用它们进行文本处理。
请解释Python中的正则表达式以及如何使用它们进行文本处理。
9 0
|
1月前
|
机器学习/深度学习 Python
请解释Python中的正则表达式是什么?并举例说明其用法。
【2月更文挑战第26天】【2月更文挑战第86篇】请解释Python中的正则表达式是什么?并举例说明其用法。
|
1月前
|
缓存 数据安全/隐私保护 Python
Python快速入门:类、文件操作、正则表达式
Python快速入门:类、文件操作、正则表达式
|
1月前
|
索引 Python
Python快速入门:Python对象
Python快速入门:Python对象
|
1月前
|
存储 设计模式 Python
Python中的类(Class)和对象(Object)
Python中的类(Class)和对象(Object)
27 0

热门文章

最新文章