Python 正则表达式
2021/5/7 22:55:10
本文主要是介绍Python 正则表达式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Python的正则表达式(一)
- 一、re库的五个主要函数
- 1、match
- 2、findall
- 3、search
- 4、sub
- 5、compile
一、re库的五个主要函数
1、match
match函数只匹配字符串中开头的字符
import re str = 'Holle World! Holle World!' match = re.match('Ho', str) match.group() 'Ho' match.start() 0 match.end() 2 match.span() (0, 2)
下面是match的参数:
re.match(pattern, string, flags=0)
flags是正则表达式修饰符,一般不用,后面不会再解释,可去正则表达式修饰符篇查看
2、findall
findall函数匹配文本中所有的字符
import re str = 'Holle World! Holle World!' findall = re.findall('ll', str) findall ['ll', 'll']
re.findall(pattern, string, flags=0)
同上
3、search
search函数只匹配一次文本,匹配后返回
import re str = 'Holle World! Holle World!' search = re.search('ol', str) search.group() 'ol' search.span() (1, 3) search.start() 1 search.end() 3
re.search(pattern, string, flags=0)
同上
4、sub
sub函数用指定的字符串去替换文本中的指定内容
import re str = 'Holle World! Holle World!' sub = re.sub('Holle', 'Hi', str) sub 'Hi World! Hi World!'
re.sub(pattern, repl, string, flags=0)
字符 | 含义 |
---|---|
pattern | 文本中的指定内容 |
repl | 指定的字符串 |
string | 文本 |
5、compile
compile 函数用于编译正则表达式,生成一个正则表达式的对象,供 match和 search 这两个函数使用。
import re str = 'Holle World! Holle World!' compile = re.compile('Ho') compile.search(str) <re.Match object; span=(0, 2), match='Ho'> compile.match(str) <re.Match object; span=(0, 2), match='Ho'> compile.search(str, 1, 25) <re.Match object; span=(13, 15), match='Ho'> compile.match(str, 1, 25) # 没有返回值 compile.match(str, 13, 25) <re.Match object; span=(13, 15), match='Ho'>
re.compile(pattern[, flags])
PS:该篇内容是对re中五个函数的一些粗略的介绍,更多内容往后继续更新!
这篇关于Python 正则表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python