新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

什么是Python正则表达式-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

站在用户的角度思考问题,与客户深入沟通,找到梅县网站设计与梅县网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都做网站、成都网站设计、成都外贸网站建设、企业官网、英文网站、手机端网站、网站推广、域名与空间、网络空间、企业邮箱。业务覆盖梅县地区。

本篇文章给大家分享的是有关什么是Python正则表达式,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1、查找第一个匹配串

s = 'i love python very much'

pat = 'python'

r = re.search(pat,s)

print(r.span()) #(7,13)

2、查找所有1

s = '山东省潍坊市青州第1中学高三1班'

pat = '1'

r = re.finditer(pat,s)

for i in r:

print(i)

 

#

#

3、\d匹配数字[0-9]

s = '一共20行代码运行时间13.59s'

pat = r'\d+' # +表示匹配数字(\d表示数字的通用字符)1次或多次

r = re.findall(pat,s)

print(r)

# ['20', '13', '59']

4、表示前一个字符匹配0或1次

s = '一共20行代码运行时间13.59s'

pat = r'\d+\.?\d+' # ?表示匹配小数点(\.)0次或1次

r = re.findall(pat,s)

print(r)

# ['20', '13.59']

5、^匹配字符串的开头

s = 'This module provides regular expression matching operations similar to those found in Perl'

pat = r'^[emrt]' # 查找以

r = re.findall(pat,s)

print(r)

# [],因为字符串的开头是字符`T`,不在emrt匹配范围内,所以返回为空

6、re.I 忽略大小写

s = 'This module provides regular expression matching operations similar to those found in Perl'

pat = r'^[emrt]' # 查找以

r = re.compile(pat,re.I).search(s)

print(r)

# 表明字符串的开头在匹配列表中

7、使用正则提取单词

s = 'This module provides regular expression matching operations similar to those found in Perl'

pat = r'\s[a-zA-Z]+'

r = re.findall(pat,s)

print(r) #[' module', ' provides', ' regular', ' expression', ' matching', ' operations', ' similar', ' to', ' those', ' found', ' in', ' Perl']

8、只捕获单词,去掉空格

s = 'This module provides regular expression matching operations similar to those found in Perl'

pat = r'\s([a-zA-Z]+)'

r = re.findall(pat,s)

print(r) #['module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']

9、补充上第一个单词

s = 'This module provides regular expression matching operations similar to those found in Perl'

pat = r'\s?([a-zA-Z]+)'

r = re.findall(pat,s)

print(r) #['This', 'module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']

10、使用split函数直接分割单词

使用以上方法分割单词,不是简洁的,仅仅为了演示。分割单词最简单还是使用 split 函数。

s = 'This module provides regular expression matching operations similar to those found in Perl'

pat = r'\s+'

r = re.split(pat,s)

print(r) # ['This', 'module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']

以上就是什么是Python正则表达式,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联-成都网站建设公司行业资讯频道。


文章题目:什么是Python正则表达式-创新互联
网站URL:http://www.wjwzjz.com/article/dpjicg.html
在线咨询
服务热线
服务热线:028-86922220
TOP