转载:https://www.cnblogs.com/yuanchenqi/article/5732581.html

就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

字符匹配(普通字符,元字符):

1 普通字符:大多数字符和字母都会和自身匹配
              >>> re.findall('alvin','yuanaleSxalexwupeiqi')
                      ['alvin']

2 元字符:. ^ $ * + ? { } [ ] | ( ) \

元字符之. ^ $ * + ? { }

import re

ret=re.findall('a..in','helloalvin')
print(ret)#['alvin'] ret=re.findall('^a...n','alvinhelloawwwn')
print(ret)#['alvin'] ret=re.findall('a...n$','alvinhelloawwwn')
print(ret)#['awwwn'] ret=re.findall('a...n$','alvinhelloawwwn')
print(ret)#['awwwn'] ret=re.findall('abc*','abcccc')#贪婪匹配[0,+oo]
print(ret)#['abcccc'] ret=re.findall('abc+','abccc')#[1,+oo]
print(ret)#['abccc'] ret=re.findall('abc?','abccc')#[0,1]
print(ret)#['abc'] ret=re.findall('abc{1,4}','abccc')
print(ret)#['abccc'] 贪婪匹配

注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配

ret=re.findall('abc*?','abcccccc')
print(ret)#['ab']

元字符之字符集[]:

#--------------------------------------------字符集[]
ret=re.findall('a[bc]d','acd')
print(ret)#['acd'] ret=re.findall('[a-z]','acd')
print(ret)#['a', 'c', 'd'] ret=re.findall('[.*+]','a.cd+')
print(ret)#['.', '+'] #在字符集里有功能的符号: - ^ \ ret=re.findall('[1-9]','45dha3')
print(ret)#['4', '5', '3'] ret=re.findall('[^ab]','45bdha3')
print(ret)#['4', '5', 'd', 'h', '3'] ret=re.findall('[\d]','45bdha3')
print(ret)#['4', '5', '3']

元字符之转义符\

反斜杠后边跟元字符去除特殊功能,比如\.
反斜杠后边跟普通字符实现特殊功能,比如\d

\d  匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s  匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
\b  匹配一个特殊字符边界,比如空格 ,&,#等

ret=re.findall('I\b','I am LIST')
print(ret)#[]
ret=re.findall(r'I\b','I am LIST')
print(ret)#['I']

现在我们聊一聊\,先看下面两个匹配:

#-----------------------------eg1:
import re
ret=re.findall('c\l','abc\le')
print(ret)#[]
ret=re.findall('c\\l','abc\le')
print(ret)#[]
ret=re.findall('c\\\\l','abc\le')
print(ret)#['c\\l']
ret=re.findall(r'c\\l','abc\le')
print(ret)#['c\\l'] #-----------------------------eg2:
#之所以选择\b是因为\b在ASCII表中是有意义的
m = re.findall('\bblow', 'blow')
print(m)
m = re.findall(r'\bblow', 'blow')
print(m)

元字符之分组()

m = re.findall(r'(ad)+', 'add')
print(m) ret=re.search('(?P<id>\d{2})/(?P<name>\w{3})','23/com')
print(ret.group())#23/com
print(ret.group('id'))#23

元字符之|

ret=re.search('(ab)|\d','rabhdg8sd')
print(ret.group())#ab

re模块下的常用方法

import re
#1
re.findall('a','alvin yuan') #返回所有满足匹配条件的结果,放在列表里
#2
re.search('a','alvin yuan').group() #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
# 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。 #3
re.match('a','abc').group() #同search,不过尽在字符串开始处进行匹配 #4
ret=re.split('[ab]','abcd') #先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
print(ret)#['', '', 'cd'] #5
ret=re.sub('\d','abc','alvin5yuan6',1)
print(ret)#alvinabcyuan6
ret=re.subn('\d','abc','alvin5yuan6')
print(ret)#('alvinabcyuanabc', 2) #6
obj=re.compile('\d{3}')
ret=obj.search('abc123eeee')
print(ret.group())#123

  

import re
ret=re.finditer('\d','ds3sy4784a')
print(ret) #<callable_iterator object at 0x10195f940> print(next(ret).group())
print(next(ret).group())

注意:

import re

ret=re.findall('www.(baidu|oldboy).com','www.oldboy.com')
print(ret)#['oldboy'] 这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可 ret=re.findall('www.(?:baidu|oldboy).com','www.oldboy.com')
print(ret)#['www.oldboy.com']

补充1:

import re

print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>"))
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>"))
print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>"))

补充2:

#匹配出所有的整数
import re #ret=re.findall(r"\d+{0}]","1-2*(60+(-40.35/5)-(-4*3))")
ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
ret.remove("") print(ret)

22.re(正则表达式)的更多相关文章

  1. 22、正则表达式(用于三剑客grep,awk,sed,内容中包含空行)

    简单的说就是为处理大量的字符串而定义的一套规则和方法,通过定义特殊符号的辅助,系统管理员就可以快速过滤,替换城输出需要的字符串 : ^:^word 表示匹配以什么字符开头的内容: $:word$表示匹 ...

  2. 《Shell十三问》笔记(下)

    继续开始shell十三问中11-13问和后续补充的笔记,加油! (14)输入重定向与输出重定向 “>”是标准输出重定向,可以把输出结果送入文件 “<”是标准输入重定向,可以重新指定文件的内 ...

  3. Perl的调试方法

    来源: http://my.oschina.net/alphajay/blog/52172 http://www.cnblogs.com/baiyanhuang/archive/2009/11/09/ ...

  4. 【持续更新】JavaScript常见面试题整理

    [重点提前说]这篇博客里的问题涉及到了了JS中常见的的基础知识点,也是面试中常见的一些问题,建议初入职场的园友Mark收藏,本文会持续更新~ 1. 引入JS的三种方式 1.在HTML标签中直接使用,直 ...

  5. MongoDB 基础(2019年开篇)

    MongoDB基础知识: 1.什么是MongoDB NoSQL(NoSQL=Not Only SQL),意即"不仅仅是SQL". MongoDB是一个介于关系数据库和非关系数据库之 ...

  6. MongoDB数据库(二):增删查改

    MongoDB数据库的增删查改 1.插入数据 语法: db.集合名称.insert(document) db.table_name.insert({name:'gj',gender:1}) db.ta ...

  7. Web前端安全之安全编码原则

    随着Web和移动应用等的快速发展,越来越多的Web安全问题逐渐显示出来.一个网站或一个移动应用,如果没有做好相关的安全防范工作,不仅会造成用户信息.服务器或数据库信息的泄露,更可能会造成用户财产的损失 ...

  8. 1.22 Python基础知识 - 正则表达式

    Python正则表达式 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配. Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式. re ...

  9. 2014.12.22 几个有用的oracle正则表达式

    SELECT REGEXP_REPLACE('LSS12345', '[^0-9]') FROM DUAL 结果:12345 '[^0-9]'中的^表示‘非’上述表达式的含义是“将LSS12345中的 ...

随机推荐

  1. 集合 Enumerable Enumerator yield

    集合: 通过索引来访问成员,--引申到索引器 的使用 for foreach循环遍历 --引申到 IEnumerable IEnumerator(会引申到yield) 常用的集合操作,add, ins ...

  2. ggplot2笔记

    ggplot2笔记 下面是ggplot2的一些文档和github上的源代码http://docs.ggplot2.org/current/https://github.com/hadley/ggplo ...

  3. javascript导图 标签: javascript 2015-12-06 16:37 721人阅读 评论(24)

  4. python基础之逻辑题(2)

    python基础之逻辑题(2) 1.若k为整数,下列while循环执行的次数为? 2.请输出正确结果-----numbers? 3.求结果-----math?   4.求结果-----sum? 5.输 ...

  5. 2019-9-30-WPF-运行时迁移-EF-Core-数据库

    title author date CreateTime categories WPF 运行时迁移 EF Core 数据库 lindexi 2019-09-30 20:19:16 +0800 2019 ...

  6. props & children

    一. choosing the type at runtime import React from 'react'; import { PhotoStory, VideoStory } from '. ...

  7. Android Xutils框架使用问题及解决办法

    刚刚写了篇博客,提了下在使用XUtils时遇到的一个问题Android Xutils框架HttpUtil Get请求缓存问题 ,既然已经提起来这个问题,那我想了下,就把之前使用Xutils时遇到的几个 ...

  8. git比较两个版本之间的区别

    查看当前没有add 的内容修改: git diff 查看已经add 没有commit 的改动 git diff --cached 查看当前没有add和commit的改动: git diff HEAD ...

  9. Vue打包后放到服务器出现Loading chunk {n} failed 错误

    导航栏点击切换时 会出现Loading chunk {n} failed  ,刷新之后便不会出现.而且n在最新的build的文件中,n没有存在 偶然一次发现,项目更新迭代开发时上传测试环境后就会出现, ...

  10. [转载] 使用StAX解析xml

    StAX 概述 从一开始,Java API for XML Processing (JAXP) 就提供了两种方法来处理 XML:文档对象模型(DOM)方法是用标准的对象模型表示 XML 文档:Simp ...