什么是Python正则表达式

发布时间:2020-08-04 17:19:11 作者:Leah
来源:亿速云 阅读:128

本篇文章给大家分享的是有关什么是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)

 

# <re.Match object; span=(9, 10), match='1'>

# <re.Match object; span=(14, 15), match='1'>

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

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

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

r = re.findall(pat,s)

print(r)

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

4、表示前一个字符匹配01

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匹配范围内,所以返回为空

6re.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)

# <re.Match object; span=(0, 1), match='T'> 表明字符串的开头在匹配列表中

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正则表达式,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 什么是python
  2. 什么是python?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 正则表达式

上一篇:学习Python能实现的实际功能有哪些

下一篇:Hive是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》