阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

简单介绍python中使用正则表达式的方法

31次阅读
没有评论

共计 1648 个字符,预计需要花费 5 分钟才能阅读完成。

导读 这篇文章主要为大家详细介绍了 python 中使用正则表达式的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

在 python 中使用正则表达式, 主要通过下面的几个方法

search(pattern, string, flags=0)

扫描整个 string 并返回匹配 pattern 的结果(None 或对象)

有匹配的字符串的话返回一个对象(包含符合匹配条件的第一个字符串), 否则返回 None

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))
findall(pattern, string, flags=0)

扫描整个 context 并返回匹配 res 的结果(None 或列表)

有匹配的字符串的话返回一个列表(符合匹配条件的每个子字符串作为它的一个元素), 否则返回 None

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')]
sub(pattern, repl, string, count=0, flags=0)

可以来修改文本

用将用 pattern 匹配 string 所得的字符串替换成 repl

import re
 
content = '54aK54yr5oiR54ix5L2g'
res = '\d+'
content = re.sub(res, '', content)
print(content)
compile(pattern, flags=0)

将正则表达式 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)
flags 的一些常用值

re.I 使匹配对大小写不敏感

re.S 使. 匹配包括换行符在内的所有字符

import re
re.compile(res, re.I)
#如果 res 可以匹配大写字母, 那它也可以匹配相应的小写字母,反之也可
 
re.compile(res,re.S)
#使 res 中的 '.' 字符可以匹配包括换行符在内的所有字符

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计1648字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中