Python 官方文档:入门教程 => 点击学习
目录search(pattern, string, flags=0)findall(pattern, string, flags=0)sub(pattern, repl, strin
import re
#导入正则库
content = 'Hello 1234567 Hello 666'
#要匹配的文本
res = 'Hello\s'
#正则字符串
result = re.search(res, content)
if result is not None:
print(result.group())
#输出匹配得到的字符串 'hello'(返回的得是第一个'hello')
print(result.span())
#输出输出匹配的范围(匹配到的字符串在原字符串中的位置的范围)
res1 = 'Hello\s(\d)(\d+)'
result = re.search(res1, content)
print(result.group(1))
#group(1)表示匹配到的第一个组(即正则字符串中的第一个括号)的内容
print(result.group(2))
import re
res = 'Hello\s'
results = re.findall(res, content)
if results is not None:
print(results)
#输出: ['hello','hello']
res1 = 'Hello\s(\d)(\d+)'
results = re.findall(res1, content)
if result is not None:
print(results)
# 当正则字符串中出现括号时,所得到列表的每个元素是元组
# 每个元组的元素都是依次匹配到的括号内的表达式的结果
#输出: [('1','1234567'),('6','666')]
import re
content = '54aK54yr5oiR54ix5L2g'
res = '\d+'
content = re.sub(res, '', content)
print(content)
将正则表达式res编译成一个正则对象并返回,以便复用
import re
content1 = '2019-12-15 12:00'
content2 = '2019-12-17 12:55'
content3 = '2019-12-22 13:21'
pattern = re.compile('\d{2}:\d{2}')
result1 = re.sub(pattern, '', content1)
result2 = re.sub(pattern, '', content2)
result3 = re.sub(pattern, '', content3)
print(result1, result2, result3)
import re
re.compile(res, re.I)
#如果res可以匹配大写字母,那它也可以匹配相应的小写字母,反之也可
re.compile(res,re.S)
#使res中的'.'字符可以匹配包括换行符在内的所有字符
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: python中使用正则表达式的方法详解
本文链接: https://www.lsjlt.com/news/144312.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0