6.25正则相关

    正则表达式简介

l 正则表达式,是一个特殊的字符序列,又称规则表达式(在代码中常简写为 RE ),是⼀种使⽤表达式的⽅式对字符串进⾏匹配的语法规则。

贪婪和非贪婪模式

Ø 贪婪模式( .* ): 尝试匹配尽可能多的字符
Ø 非贪婪模式( .*? : 尝试匹配尽可能少的字符(匹配到结果就行)

        当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串 "oooo"'o+?' 将匹配单个 "o",而 'o+' 将匹配所有 'o'

基础正则符号

\w

匹配字母数字及下划线

\W

匹配非字母数字及下划线

\s

匹配任意空白字符,等价于 [\t\n\r\f].

\S

匹配任意非空字符

\d

匹配任意数字,等价于 [0-9].

\D

匹配任意非数字

\A

匹配字符串开始^

\Z

匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。$

\z

匹配字符串结束

\G

匹配最后匹配完成的位置。

\n, \t, 等.

匹配一个换行符。匹配一个制表符。等

正则模块的用法

python中,如果使用正则表达式的话,需要导入re模块,re模块是一个内置模块,直接import就可以使用,下面是re模块中的核心函数。

自定义正则规则

一、校验数字的表达式

数字 ^[0-9]*$
n 位的数字 ^\d{n}$
至少 n 位的数字: ^\d{n,}$
m- n 位的数字 ^\d{ m,n }$
零和非零开头的数字: ^(0| 1-9 *)$
非零开头的最多带两位小数的数字: ^( 1-9 *)+(.[0-9]{1,2})?$
1-2 位小数的正数或负数: ^(-)?\d+(.\d{1,2})?$
正数、负数、和小数: ^(-|+)?\d+(.\d+)?$
有两位小数的正实数: ^[0-9]+(.[0-9]{2})?$
非负整数 ^\d+$ ^[1-9]\d*|0$
非正整数 ^-[1-9]\d*|0$ ^((-\d+)|(0+))$
浮点数: ^(-?\d+)(.\d+)?$ ^-?([1-9]\d .\d |0.\d [1-9]\d |0?.0+|0)$

二、校验字符的表达式

汉字 ^[\u4e00-\u9fa5]{0,}$
英文和数字 ^[A-Za-z0-9]+$ ^[A-Za-z0-9]{4,40}$
长度为 3-20 的所有字符: ^.{3,20}$
26 个英文字母组成的字符串: ^[A-Za-z]+$
26 大写英文字母组成的字符串: ^[A-Z]+$
26 个小写英文字母组成的字符串: ^[a-z]+$
由数字和 26 个英文字母组成的字符串: ^[A-Za-z0-9]+$
由数字、 26 个英文字母或者下划线组成的字符串: ^\w+$ ^\w{3,20}$
中文、英文、数字包括下划线 ^[\u4E00-\u9FA5A-Za-z0-9_]+$
中文、英文、数字但不包括下划线等符号 ^[\u4E00-\u9FA5A-Za-z0-9]+$ ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$
可以输入含有 ^%&’,;=?$\” 等字符: %&',;=?$\x22+
禁止输入含有 ~ 的字符: ~\x22+

•三.正则分割,正则分组

split 方法按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下:

re.split(pattern, string[, maxsplit=0, flags=0])

正则例题

1 匹配指定内容

import re
s = 'i love python very much'
pat = 'python'
r = re.search(pat,s)
print(r.group())

2 查找所有1

import re
s = '山东省潍坊市青州第1中学高三1班'
pat = '1'
r = re.finditer(pat,s)
for i in r:
    print(i) # span 下标
    print(i.group())

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

s = '一共20行代码运行时间13.59s'
pat = r'\d+' # +表示匹配数字(\d表示数字的通用字符)1次或多次
r = re.findall(pat,s)
print(r)
# ['20', '13', '59']

import re
s = '一共20行代码运行时间13.59s'
pat = r'\d+' # +表示匹配数字(\d表示数字的通用字符)1次或多次
r = ' '.join(re.findall(pat,s))
print(r)

我们想保留13.59而不是分开,请看4

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

import re
s = '一共20行代码运行时间13.59s'
pat = r'\d+\.?\d+' # ?表示匹配小数点(\.)0次或1次
r = re.findall(pat,s)
print(r)

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

7 使用正则提取单词

这是不准确版本,请参看第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) #[' module', ' provides', ' regular', ' expression', ' matching', ' operations', ' similar', ' to', ' those', ' found', ' in', ' Perl']

8 只捕获单词,去掉空格

使用()捕获,这是不准确版本,请参看第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) #['module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']

9 补充上第一个单词

上面第8,看到提取单词中未包括第一个单词,使用?表示前面字符出现0次或1次,但是此字符还有表示贪心或非贪心匹配含义,使用时要谨慎。

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']

11 提取以mt开头的单词,忽略大小写

下面出现的结果不是我们想要的,原因出在 ?上!

s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s?([mt][a-zA-Z]*)' # 查找以
r = re.findall(pat,s)
print(r) # ['module', 'matching', 'tions', 'milar', 'to', 'those']

12 使用^查找字符串开头的单词

综合11和12得到所有以m或t开头的单词

s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'^([mt][a-zA-Z]*)\s' # 查找以
r = re.compile(pat,re.I).findall(s)
print(r) # ['This']

13 先分割,再查找满足要求的单词

使用match表示是否匹配

s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s+' 
r = re.split(pat,s)
res = [i for i in r if re.match(r'[mMtT]',i)]
print(res) # ['This', 'module', 'matching', 'to', 'those']

14 贪心匹配

尽可能多的匹配字符

content='<h>ddedadsad</h><div>graph</div>bb<div>math</div>cc'
pat=re.compile(r"<div>(.*)</div>")  #贪婪模式
m=pat.findall(content)
print(m) # ['graph</div>bb<div>math']

15 非贪心匹配

与14相比,仅仅多了一个问号(?),得到结果完全不同。

content='<h>ddedadsad</h><div>graph</div>bb<div>math</div>cc'
pat=re.compile(r"<div>(.*?)</div>")  #贪婪模式
m=pat.findall(content)
print(m) # ['graph', 'math']

与14比较可知,贪心匹配和非贪心匹配的区别,后者是字符串匹配后立即返回,见好就收。

16 含有多种分割符

使用split函数

content = 'graph math,,english;chemistry' # 这种
pat=re.compile(r"[\s\,\;]+")  #贪婪模式
m=pat.split(content)
print(m) # ['graph', 'math', 'english', 'chemistry']

17 替换匹配的子串

sub函数实现对匹配子串的替换

content="hello 12345, hello 456321"   
pat=re.compile(r'\d+') #要替换的部分
m=pat.sub("666",content)
print(m) # hello 666, hello 666

18 爬取百度首页标题

import re
from urllib import request

#爬虫爬取百度首页内容
data=request.urlopen("http://www.baidu.com/").read().decode()

#分析网页,确定正则表达式
pat=r'<title>(.*?)</title>'

result=re.search(pat,data)
print(result) <re.Match object; span=(1358, 1382), match='<title>百度一下,你就知道</title>'>

result.group() # 百度一下,你就知道

19 常用元字符总结复习

. 匹配任意字符 
^ 匹配字符串始位置
$ 匹配字符串中结束的位置
* 前面的原子重复0次1次多次
? 前面的原子重复一次或者0次
+ 前面的原子重复一次或多次
{n} 前面的原子出现了 n 次
{n,} 前面的原子至少出现 n 次
{n,m} 前面的原子出现次数介于 n-m 之间
( ) 分组,需要输出的部分

20 常用通用字符总结复习

\s  匹配空白字符
\w  匹配任意字母/数字/下划线
\W  和小写 w 相反,匹配任意字母/数字/下划线以外的字符
\d  匹配十进制数字
\D  匹配除了十进制数以外的值
[0-9]  匹配一个0-9之间的数字
[a-z]  匹配小写英文字母
[A-Z]  匹配大写英文字母

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值