python笔记08-----正则表达式
创建正则表达式对象
import re
常用匹配语法
re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub 匹配字符并替换
re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') 创建匹配对象
常用正则表达式符号
. 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
^ 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r”^a”,”\nabc\neee”,flag=re.MULTILINE)
$ 匹配字符串结尾,或e.search(”foo$”,”bfoo\nnsdfsf”,flags=re.MULTILINE).group()也可以
* 匹配*号前的字符0次或多次,re.findall(“ab*”,”cabb3abcbbac”) 结果为[‘abb’,’ab’,’a’]
+ 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") ['ab', 'abb']
? 匹配前一个字符1次或0次
{m}匹配前一个字符m次 re.findall("b{3}","ab+cd+abbb+bba") ['bbb']
{n,m} 匹配前一个字符n到m次 re.findall("b{1,2}","ab+cd+abbb+bba") ['b', 'bb', 'b', 'bb'] 后边加问好是匹配最少 不加则是最多
| 匹配|左或|右的字符 re.findall("b|c","ab+cd+abbb+bba") ['b', 'c', 'b', 'b', 'b', 'b', 'b']
(...)分组匹配
\A 只从字符开头匹配
\Z 匹配字符结尾 同$
\d 匹配数字0-9
\D 匹配非数字
\w 匹配[A-Za-z0-9]
\W匹配非[A-Za-z0-9]
\s 匹配空白字符。\t \n \r
\S匹配除了空白字符。\t \n \r
(?P<name>…)分组匹配
匹配实例
1.创建匹配对象compile()方法
import re
a = re.compile(r'\d+')
a1 = a.search('gfd12341ahvcnxjbkafa')
print (a1.group()) # .group()直接输出结果,而不是返回对象
结果
2.从头开始匹配 match()方法
import re
a = re.match("^w.+", "wdasfdsafdsa1223fdssfd33311")
b = re.match("^[a-z]+", "wdasfdsafdsa1223fdssfd33311")
c = re.search("R[a-zA-z]+a", "wdasfdsafdsa1223fdssfd33311")
print (a)
print (b)
print (c)
结果如下
<_sre.SRE_Match object; span=(0, 27), match='wdasfdsafdsa1223fdssfd33311'>
<_sre.SRE_Match object; span=(0, 12), match='wdasfdsafdsa'>
None
3.匹配包含search()方法
import re
a = re.search("[a-z]+","abcdefg12345")
print (a.group())
结果如下
abcdefg
4.管道匹配多个分组 |
import re
hero = re.compile(r'ABC|DEF')
m1 = hero.search('ABC hehe ABC')
print (m1.group())
m2 = hero.search('DEF hehe ABC')
print (m2.group())
结果如下
ABC
DEF
5.分组匹配 () 和group()
import re
phoneNum = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNum.search('my number is 415-555-4242')
print (mo.group(1)) #输出第一个组
print (mo.group(2)) #输出第二个组
print (mo.group(0)) #输出所有
print (mo.group()) #输出所有
结果
555-4242
415-555-4242
415-555-4242
6.用问号实现可选匹配
import re
b = re.compile(r'Bat(wo)?man')
mo = b.search('The Adventures of Batman')
print (mo.group())
mo1 = b.search('The Adventures of Batwoman')
print (mo1.group())
结果
Batman
Batwoman
7.用星号匹配零次或多次
import re
b = re.compile(r'Bat(wo)*man')
mo = b.search('The Adventures of Batman')
print (mo.group())
mo1 = b.search('The Adventures of Batwoman')
print (mo1.group())
mo2 = b.search('The Adventures of Batwowowowowoman')
print (mo2.group())
结果
Batman
Batwoman
Batwowowowowoman
8.用+号匹配一次或多次
import re
b = re.compile(r'Bat(wo)+man')
mo = b.search('The Adventures of Batwoman')
print (mo.group())
mo1 = b.search('The Adventures of Batwoman')
print (mo1.group())
mo2 = b.search('The Adventures of Batwowowowowoman')
print (mo2.group())
结果
Batwoman
Batwoman
Batwowowowowoman
9.用花括号匹配特定次数
import re
b = re.compile(r'(ha){3}')
mo = b.search('hahahahahaha')
print (mo.group())
结果
hahaha
10.花括号匹配最多和最少次数
import re
b = re.compile(r'(ha){3,5}') #匹配3到5次
mo = b.search('hahahahahaha') #什么都不加默认匹配最多个
print (mo.group())
b1 = re.compile(r'(ha){3,5}?') #加问号匹配最少的个数
mo1 = b1.search('hahahahahaha')
print (mo1.group())
结果
hahahahaha
hahaha
11.findall()方法
import re
b = re.compile(r'\d\d\d\d-\d\d\d\d')
mo = b.findall('call: 1234-4321 work:8521-5155')
print (mo)
返回结果列表
['1234-4321', '8521-5155']
分组匹配
import re
b = re.compile(r'(\d\d\d\d)-(\d\d\d\d)')
mo = b.findall('call: 1234-4321 work:8521-5155')
print (mo)
返回结果列表 元组
[('1234', '4321'), ('8521', '5155')]
12.建立自己的字符分类
匹配[]中的元素 和匹配除[]中的元素
import re
v = re.compile(r'[^abc]')
v1 = v.findall('gafeagbbbbfsdgfaccsgzfevcsdfdf')
print (v1)
q = re.compile(r'[abc]')
q1 = q.findall('gafeagbbbbfsdgfaccsgzfevcsdfdf')
print (q1)
结果
['g', 'f', 'e', 'g', 'f', 's', 'd', 'g', 'f', 's', 'g', 'z', 'f', 'e', 'v', 's', 'd', 'f', 'd', 'f']
['a', 'a', 'b', 'b', 'b', 'b', 'a', 'c', 'c', 'c']
13.不区分大小写匹配 re.IGNORECASE或re.I
import re
a = re.compile(r'efg', re.I)
print (a.search('ABCDEFG').group())
结果
EFG
14.sub()方法替换字符串
import re
a = re.compile(r'ABC')
print (a.sub(r'123','ABCDEFG'))
结果
123DEFG
sub支持函数调用
import re
def add(tmp):
strnum = tmp.group()
num = int(strnum) + 1
return str(num)
ret = re.sub(r'\d+', add, "python = 123")
print (ret)
ret = re.sub(r'\d+', add, "python = 12")
print (ret)
输出结果
python = 124
python = 13
15.管理复杂的正则表达式re.VERBOSE
import re
a = re.compile(r'''(
(\d{3}|\(\d{3}\))? #注释
)''',re.VERBOSE)
b = a.search('123,32141,321,fdsafdgdacszc')
print (b.group())
看结果
16.split根据匹配进行切割字符串,并返回一个列表
import re
ret = re.split(r":| ", "oh:my:god | nonono")
print (ret)
['oh', 'my', 'god ' ,'nonono']
正则表达式符号总结
? 匹配零次或一次前面的分组
* 匹配零次或多次前面的分组
+ 匹配一次或多次前面的分组
{n} 匹配n次前面的分组
{n,} 匹配n次或更多前面的分组
{,m} 匹配零次到m次前面的分组
{n,m} 匹配至少n次,至多m次前面的分组
{n,m} ?或*?或+?对前面的分组进行最少/最多次匹配
^spam 意味着字符串必须以spam开始
spam$ 意味着字符串必须以spam结束
. 匹配所有字符,换行符除外
\d \w \s 分别匹配数字,单词和空格
\D \W \S 分别匹配出数字,单词和空格外的所有字符
[abc] 匹配中括号内的任意字符(a,b或c)
[^abc] 匹配不在中括号内的任意字符
如果想匹配. * +这样的字符 请用转义字符\,如\. \* \+
其他的匹配符号大家可以自己去组合去尝试,这里不一一列举了
练习:校验手机号
import re r = re.compile(r'^1[3-9][0-9]{9}$') print(r.match(""))
print(r.match(""))
print(r.match(""))
print(r.match("1a222222222"))
print(r.match(""))
结果为
None
<re.Match object; span=(0, 11), match='13333333333'>
<re.Match object; span=(0, 11), match='13671273333'>
None
<re.Match object; span=(0, 11), match='17600259711'>
python笔记08-----正则表达式的更多相关文章
- Python:笔记(6)——正则表达式
Python:笔记(6)——正则表达式 re模块 re模块用于在字符串中执行基于正则表达式模式的匹配和替换. 使用原始字符串 正则表达式使用 \ 对特殊字符进行转义,比如,为了匹配字符串 ‘pytho ...
- Python笔记 #08# NumPy: Statistic Basis
数据分析的基本步骤: 了解你的数据(get to know your data), 做一些统计学处理(像僵尸一样盯着数字不会带给你任何灵感!) 实现可视化(get a better feeling f ...
- [Python笔记]第九篇:re正则表达式
一.正则表达式基础 1.正则表达式介绍 正则表达式并不是Python的一部分.正则表达式是用于处理字符串的强大工具,拥有自己独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十分 ...
- [Python笔记][第四章Python正则表达式]
2016/1/28学习内容 第四章 Python字符串与正则表达式之正则表达式 正则表达式是字符串处理的有力工具和技术,正则表达式使用预定义的特定模式去匹配一类具有共同特征的字符串,主要用于字符串处理 ...
- Python学习笔记013_正则表达式
Python中的正则表达式是通过 re 模块实现的. 通配符 . 表示除了换行以外的任何字符; 编写正则表达式时使用 r're' , r + 正则表达式内容 >>> impor ...
- Python笔记之不可不练
如果您已经有了一定的Python编程基础,那么本文就是为您的编程能力锦上添花,如果您刚刚开始对Python有一点点兴趣,不怕,Python的重点基础知识已经总结在博文<Python笔记之不可不知 ...
- python笔记 - day6
python笔记 - day6 参考: http://www.cnblogs.com/wupeiqi/articles/5501365.html 大纲: 利用递归,实现阶乘: Python反射 pyt ...
- python笔记之常用模块用法分析
python笔记之常用模块用法分析 内置模块(不用import就可以直接使用) 常用内置函数 help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像 ...
- s21day25 python笔记
s21day25 python笔记 正则表达式 1.定义 定义:正则表达式是一种规则匹配字符串的规则 re模块本身只是用来操作正则表达式的,和正则本身没关系 为什么要有正则表达式? 匹配字符串 一个人 ...
- python进阶11 正则表达式
python进阶11 正则表达式 一.概念 #正则表达式主要解决什么问题? #1.判断一个字符串是否匹配给定的格式,判断用户提交的又想的格式是否正确 #2.从一个字符串中按指定格式提取信息,抓取页面中 ...
随机推荐
- 将图片流输出到界面mvc
System.Drawing.Image _CodeImage = _Code39.GetCodeImage(OrderNo, Code39.Code39Model.Code39Normal, tru ...
- ie11 兼容的问题
碰到一个问题 下拉列表点不了. 测试后,只在ie11下有这个问题. 先是在head 加<meta http-equiv=”X-UA-Compatible” content="IE=8& ...
- Visual Studio for mac从入门到放弃1
MAC 第一步:从微软官网下载:https://www.visualstudio.com/vs/visual-studio-mac/ 第二步:安装软件过程出现 It was not possible ...
- 10-06 Linux的基本命令以及一些简单的通配符说明
Shell的通配符 主要用于模式匹配,如:文件名匹配,路径名搜索,字符查找等.常用的有:'*','?','[]' '*':代表任意长度的字串. '?':代表单个任意字符 '[]':代表模式串匹配的字符 ...
- ASP.NET添加Mysql数据源
在ASP.NET的数据源控件上添加mysql数据库连接,首先需要在windows系统下添加mysql的数据源才能在vs中添加数据源 1.在控制面板下打开系统与安全-->打开管理工具-->点 ...
- JPA之@GeneratedValue注解
JPA的@GeneratedValue注解,在JPA中,@GeneratedValue注解存在的意义主要就是为一个实体生成一个唯一标识的主键(JPA要求每一个实体Entity,必须有且只有一个主键), ...
- python--面向对象(02)
1.类的成员 在类中你能写的所有内容都是类的成员 class 类名: # 方法 def __init__(self, 参数1, 参数2....): # 属性变量量 self.属性1 = 参数1 sel ...
- 快速排序 JAVA实现
快速排序 每次排序的时候设置一个基准点,将小于等于基准点的数全部放到基准点的左边,将大于等于基准点的数全部放到基准点的右边.快速排序是不稳定的,时间复杂度(平均):nlogn public class ...
- 552. Student Attendance Record II
Given a positive integer n, return the number of all possible attendance records with length n, whic ...
- 水平居中和transform: translateY(-50%) 实现元素垂直居中效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...