python re 模块和基础正则表达式
1.迭代器:对象在其内部实现了iter(),__iter__()方法,可以用next方法实现自我遍历。
二.python正则表达式
1.python通过re模块支持正则表达式
2.查看当前系统有哪些python模块:help('modules')
help():交互式模式,支持两种方式调用(交互式模式调用,函数方式调用)
例:交互式调用
>>> help()
Welcome to Python 3.5's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> modules
函数式调用
help('modules')
3.正则表达式的元字符
\s :空白符;
\S :非空白符;
[\s\S] :任意字符;
[\s\S]* :0个到多个任意字符;
[\s\S]*? : 0个字符,匹配任何字符前的位置;
\d:数字;
\B:非数字 ;
\w:匹配单词 单词等价于:[a-zA-Z0-9_];
\W:匹配非单词;
规则:
. 匹配任意单个字符;
* 匹配前一个字符0次或多次;
+ 匹配前一个字符1次或多次;
? 匹配前一个字符0次或一次;
{m} 匹配前一个字符m次;
{m,n} 匹配前一个字符 m - n 次;
{m,} 匹配前一外字符至少 m次 至多无限次;
{,n} 匹配前一个字符 0 到 n次;
\ 转义字符;
[...] 字符集 例:[a-z];
.*? *? +? ?? {}? 使* + 等 变成非贪婪模式
边界匹配(不消耗待匹配的待匹配字符串的字符)
^:匹配字符串开头,在多行模式中匹配每一行的行首;
$:匹配字符串结尾,在多行模式中匹配每一行的行尾;
\b:匹配单词边界,不匹配任何字符,\b匹配的只是一个位置,这个位置的一侧是构成单词的字符,另一侧为非字符、字符串的开始或结束位置,\b是零宽度的。(“单词”是由\w所定义的单词子串) \b相当于:(?<!\w)(?=\w)|(?<=\w)(?!\w);
\B:[^\b];
\A:仅匹配字符串开头;
\Z:仅匹配字符串结尾;
分组:
| 或,左右表达式任意匹配一个,它先尝试匹配 | 左边的表达式,如果匹配成功则跳过匹配右边的表达式;如果 | 没有被包括在()中,则它在范围是整个正则表达式。
() 分组 ;从表达式左边开始,第遇到一个分组,编号加1;分组表达式作为一个整体,后面可接数量词;分组表达式中的 | 仅在该分组中有效。 例:(abc){3} (abc|def)123 (abc|def){3}123
\number 引用编号为 number 的分组匹配到的字符串。 例:(\d)([a-z])\1\2
环视(lookhead)
(?=) :顺序肯定环视
(?!) :顺序否定环视
(?<=) :逆序肯定环视
(?<!) :逆序否定环视
4.调用re的内置方法完成正则表达式分析
5.match(匹配)对象:
match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.
m = re.match('a','abc')
所有:
m.end m.group m.lastgroup m.re m.start
m.endpos m.groupdict m.lastindex m.regs m.string
m.expand m.groups m.pos m.span
group([group1, …]):
获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
groups([default]):
以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
m.pos (pos:postion):返回从哪个位置开始搜索
m.endpos:返回从哪个位置结束搜索
m.start():返回指定pattern在作匹配时所截获的子串在原串的起始位置
m.end():返回指定pattern在作匹配时所截获的子串在原串的结束位置
6.search:执行正则表达式搜索并且在搜索结束后返回所匹配到的串,只返回第一次匹配到的结果
search(pattern, string, flags=0)
Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found.
m.group()
m.groups()
7.findall :匹配所有的对象,返回一个列表
findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.
直接打印结果
8.finditer(用的不多)
finditer(pattern, string, flags=0)
Return an iterator(迭代器) over all non-overlapping matches in the
string. For each match, the iterator returns a match object.
Empty matches are included in the result.
9.split
split(pattern, string, maxsplit=0, flags=0)
Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list.
例:a = re.split('\.','www.baidu.com')
直接打印结果
10.sub:实现查找替换
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used.
例:In [47]: re.sub('baidu','BAIDU','www.baidu.com')
Out[47]: 'www.BAIDU.com'
11.subn :查找替换,并显示替换的次数
例:
In [48]: re.subn('baidu','BAIDU','www.baidu.com')
Out[48]: ('www.BAIDU.com', 1)
flags:
re.I或IGNORECASE:忽略字符大小写
re.M或MULTILINE:多行匹配
re.A或ASCII:仅执行8位的ASCII码字符匹配
re.U或UNICODE:使用\w,\W
re.S (DOTALL): "." matches any character at all, including the newline. 使 . 可以匹配 \n 符。
re.X (VERBOSE): Ignore whitespace and comments for nicer looking RE's. 允许在正则表达式规则中加入注释,但默认会去掉所有空格。
12.去除优先捕获:
xxx(?:)xxx
?: :分组时去除优先捕获
?P<> :
(?P<name>...)
Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.
Named groups can be referenced in three contexts. If the pattern is (?P<quote>['"]).*?(?P=quote) (i.e. matching a string quoted with either single or double quotes):
Context of reference to group “quote” Ways to reference it
in the same pattern itself
(?P=quote) (as shown)
\1
when processing match object m
m.group('quote')
m.end('quote') (etc.)
in a string passed to the repl argument of re.sub()
\g<quote>
\g<1>
\1
python re 模块和基础正则表达式的更多相关文章
- python 3.x 爬虫基础---正则表达式
python 3.x 爬虫基础 python 3.x 爬虫基础---http headers详解 python 3.x 爬虫基础---Urllib详解 python 3.x 爬虫基础---Requer ...
- Python 常用模块之re 正则表达式的使用
re模块用来使用正则表达式.正则表达式用来对字符串进行搜索的工作.我们最应该掌握正则表达式的查询,更改,删除的功能.特别是做爬虫的时候,re模块就显得格外重要. 1.查询 import re a = ...
- Python re模块前的正则表达式常用语法小总结
一.正则表达式: (1).正则表达式是干什么的 正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串.将匹配的子串替换或 ...
- python re模块常用的正则表达式
'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r&qu ...
- python 3.x 爬虫基础---Requersts,BeautifulSoup4(bs4)
python 3.x 爬虫基础 python 3.x 爬虫基础---http headers详解 python 3.x 爬虫基础---Urllib详解 python 3.x 爬虫基础---Requer ...
- Py修行路 python基础 (二十一)logging日志模块 json序列化 正则表达式(re)
一.日志模块 两种配置方式:1.config函数 2.logger #1.config函数 不能输出到屏幕 #2.logger对象 (获取别人的信息,需要两个数据流:文件流和屏幕流需要将数据从两个数据 ...
- python基础——正则表达式
正则表达式 正则表达式为高级的文本模式匹配.抽取.与/或文本形式的搜索和替换功能提供了基础.简单的说,正则表达式是一些由字符和特殊符号组成的字符串,他们描述了模式的重复或者表述多个字符,于是正则表达式 ...
- python常用模块(1):collections模块和re模块(正则表达式详解)
从今天开始我们就要开始学习python的模块,今天先介绍两个常用模块collections和re模块.还有非常重要的正则表达式,今天学习的正则表达式需要记忆的东西非常多,希望大家可以认真记忆.按常理来 ...
- python基础===正则表达式(转)
正则表达式是一个很强大的字符串处理工具,几乎任何关于字符串的操作都可以使用正则表达式来完成,作为一个爬虫工作者,每天和字符串打交道,正则表达式更是不可或缺的技能,正则表达式的在不同的语言中使用方式可能 ...
随机推荐
- 委托的N种写法,你喜欢哪种?
一.委托调用方式 1. 最原始版本: delegate string PlusStringHandle(string x, string y); class Program { static void ...
- IOS开发基础知识--碎片1
一:NSString与NSInteger的互换 NSInteger转化NSString类型:[NSString stringWithFormat: @"%d", NSInteger ...
- iOS可执行文件瘦身方法
缩减iOS安装包大小是很多中大型APP都要做的事,一般首先会对资源文件下手,压缩图片/音频,去除不必要的资源.这些资源优化做完后,我们还可以尝试对可执行文件进行瘦身,项目越大,可执行文件占用的体积越大 ...
- 代替Reflection(反射)的一些方法
Reflection(反射)是深入学习.Net必须掌握的技能之一.最初学Reflection的时候,的确是被惊住了,原来还可以这样.只要给你一个Assembly, 你就能获取到其中所有的类型,根据类型 ...
- iPhone 6 被盗记录二【写在315前夕:苹果售后福州直信创邺在没有三包的情况下帮小偷翻新、助力小偷换机销赃!无视王法。让人震惊,痛心,憎恨!消费者很受伤很无奈】
投诉公司: 北京直信创邺数码科技有限公司 标题: 写在315前夕:苹果售后在没有三包的情况下帮小偷翻新.助力小偷换机销赃!无视王法.让人震惊,痛心,憎恨!消费者很受伤很无奈 期望: 还我手机,或者赔 ...
- Redhat Server 5.7 安装配置PHP
PHP的简介 PHP于1994年由Rasmus Lerdorf创建,刚刚开始是Rasmus Lerdorf 为了要维护个人网页而制作的一个简单的用Perl语言编写的程序.这些工具程序用来显示 Rasm ...
- .NET重构—单元测试的代码重构
阅读目录: 1.开篇介绍 2.单元测试.测试用例代码重复问题(大量使用重复的Mock对象及测试数据) 2.1.单元测试的继承体系(利用超类来减少Mock对象的使用) 2.1.1.公用的MOCK对象: ...
- DB监控-Riak集群监控
公司的Riak版本是2.0.4,目前已根据CMDB三级业务部署了十几套集群,大部分是跨机房部署.监控采集分为两个大的维度,第一个维度是单机,也就是 「IP:端口」:第二个维度是集群,也就是所有节点指标 ...
- python线程池实现
python 的线程池主要有threadpool,不过它并不是内置的库,每次使用都需要安装,而且使用起来也不是那么好用,所以自己写了一个线程池实现,每次需要使用直接import即可.其中还可以根据传入 ...
- Linux 服务器模型小结
当我们用socket进行编程的时候,细节上都是选择一个AF_LOCAL,AF_INET再根据相应的类型填充地址,其实根据通信需求,有几种简单的服务模型可供选用,掌握了这些框架再结合socket高度的抽 ...