当前位置:Gxlcms > Python > python的正则表达式re模块的常用方法

python的正则表达式re模块的常用方法

时间:2021-07-01 10:21:17 帮助过:30人阅读

1.re的简介
使用python的re模块,尽管不能满足所有复杂的匹配情况,但足够在绝大多数情况下能够有效地实现对复杂字符串的分析并提取出相关信息。python 会将正则表达式转化为字节码,利用 C 语言的匹配引擎进行深度优先的匹配。

代码如下:


import re
print re.__doc__



可以查询re模块的功能信息,下面会结合几个例子说明。

2.re的正则表达式语法

正则表达式语法表如下:

语法 意义 说明
"." 任意字符
"^" 字符串开始 '^hello'匹配'helloworld'而不匹配'aaaahellobbb'
"$" 字符串结尾 与上同理
"*"
0 个或多个字符(贪婪匹配)
<*>匹配chinaunix
"+"
1 个或多个字符(贪婪匹配
与上同理
"?"
0 个或多个字符(贪婪匹配
与上同理
*?,+?,??
以上三个取第一个匹配结果(非贪婪匹配 <*>匹配</SPAN><BR></TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">{m,n}</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">对于前一个字符重复m到n次,{m}亦可</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">a{6}匹配6个a、a{2,4</SPAN><SPAN style="FONT-SIZE: 14px">}匹配2到4个a</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">{m,n}?</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px; WHITE-SPACE: normal">对于前一个字符重复m到n次,并取尽可能少</SPAN><SPAN style="FONT-SIZE: 14px"></SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">‘aaaaaa</SPAN><SPAN style="FONT-SIZE: 14px">'中a{2,4}只会匹配2个</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">"\\"</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">特殊字符转义或者特殊序列</SPAN> </TD> <TD><BR></TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">[]</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">表示一个字符集</SPAN> </TD> <TD><SPAN style="FONT-SIZE: 14px">[0-9]、[a-z</SPAN><SPAN style="FONT-SIZE: 14px">]、[A-Z</SPAN><SPAN style="FONT-SIZE: 14px">]、[^0]</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">"|"</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">或</SPAN> </TD> <TD><SPAN style="FONT-SIZE: 14px">A|B,或运算</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">(...)</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配括号中任意表达式</SPAN> </TD> <TD><BR></TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">(?#...)</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">注释,可忽略</SPAN> </TD> <TD><BR></TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">(?=...)</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">Matches if ... matches next, but doesn't consume the string.</SPAN><SPAN style="FONT-SIZE: 14px"></SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">'(?=test)' </SPAN><SPAN style="FONT-SIZE: 14px">在hellotest中匹配hello</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">(?!...)</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">Matches if ... doesn't match next.</SPAN><SPAN style="FONT-SIZE: 14px"></SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px; WHITE-SPACE: normal">'(?!=test)'</SPAN><SPAN style="FONT-SIZE: 14px"> </SPAN><SPAN style="FONT-SIZE: 14px">若hello后面不为test,匹配hello</SPAN><BR></TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">(?<=...) </SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">Matches if preceded by ... (must be fixed length).</SPAN><SPAN style="FONT-SIZE: 14px"></SPAN><BR></TD> <TD><SPAN style="WHITE-SPACE: normal"><SPAN style="FONT-SIZE: 14px">'(?<=hello</SPAN><SPAN style="FONT-SIZE: 14px">)test' </SPAN></SPAN><SPAN style="FONT-SIZE: 14px">在hellotest中匹配test</SPAN><BR></TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">(?<!...)</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">Matches if not preceded by ... (must be fixed length).</SPAN><SPAN style="FONT-SIZE: 14px"></SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px; WHITE-SPACE: normal">'(?<!hello)</SPAN><SPAN style="FONT-SIZE: 14px">test' 在hellotest中不匹配test</SPAN><BR></TD></TR></TBODY></TABLE><BR>正则表达式特殊序列表如下: <br><br> <TABLE style="WIDTH: 60%" borderColor=#000000 cellSpacing=0 cellPadding=2 border=1> <TBODY> <TR> <TD><SPAN style="FONT-SIZE: 14px; WHITE-SPACE: normal">特殊序列符号</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">意义</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\A</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">只在字符串开始进行匹配</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\Z</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">只在字符串结尾进行匹配</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\b</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配位于开始或结尾的空字符串</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\B</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配不位于开始或结尾的空字符串</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\d</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">相当于[0-9]</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\D</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">相当于[^0-9]</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\s</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配任意空白字符:[\t\n\r\r\v]</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\S</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配任意非空白字符:</SPAN><SPAN style="FONT-SIZE: 14px; WHITE-SPACE: normal">[^\t\n\r\r\v</SPAN><SPAN style="FONT-SIZE: 14px; WHITE-SPACE: normal">]</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\w</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配任意数字和字母:[a-zA-Z0-9]</SPAN> </TD></TR> <TR> <TD><SPAN style="FONT-SIZE: 14px">\W</SPAN><BR></TD> <TD><SPAN style="FONT-SIZE: 14px">匹配任意非数字和字母:[^a-zA-Z0-9]</SPAN> </TD></TR></TBODY></TABLE><BR> <P><STRONG>3.re的主要功能函数</STRONG></P> <P> 常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)<BR>compile<BR>re.compile(pattern[, flags])<BR>作用:把正则表达式语法转化成正则表达式对象<BR>flags定义包括:<BR>re.I:忽略大小写<BR>re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境<BR>re.M:多行模式<BR>re.S:' . '并且包括换行符在内的任意字符(注意:' . '不包括换行符)<BR>re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库</P> <P>search<BR>re.search(pattern, string[, flags])<BR>search (string[, pos[, endpos]])<BR>作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。</P> <P>match<BR>re.match(pattern, string[, flags])<BR>match(string[, pos[, endpos]])<BR>作用:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。</P> <P><STRONG>下面是几个例子:<BR></STRONG>例:最基本的用法,通过re.RegexObject对象调用</P> <P><div class="codetitle"><span><U></U></span> 代码如下:</p><div class="codebody" id="code63870"><BR>#!/usr/bin/env python<BR>import re<BR>r1 = re.compile(r'world')<BR>if r1.match('helloworld'):<BR> print 'match succeeds'<BR>else:<BR> print 'match fails'<BR>if r1.search('helloworld'):<BR> print 'search succeeds'<BR>else:<BR> print 'search fails' <BR></p></P> <P>说明一下:r是raw(原始)的意思。因为在表示字符串中有一些转义符,如表示回车'\n'。如果要表示\表需要写为'\\'。但如果我就是需要表示一个'\'+'n',不用r方式要写为:'\\n'。但使用r方式则为r'\n'这样清晰多了。</P> <P>例:设置flag<BR><div class="codetitle"><span><U></U></span> 代码如下:</p><div class="codebody" id="code41844"><BR>#r2 = re.compile(r'n$', re.S)<BR>#r2 = re.compile('\n$', re.S)<BR>r2 = re.compile('World$', re.I)<BR>if r2.search('helloworld\n'):<BR> print 'search succeeds'<BR>else:<BR> print 'search fails' <BR></p><BR>例:直接调用<BR><div class="codetitle"><span><U></U></span> 代码如下:</p><div class="codebody" id="code81365"><BR>if re.search(r'abc','helloaaabcdworldn'):<BR> print 'search succeeds'<BR>else:<BR> print 'search fails' <BR></p></P> <P>split<BR>re.split(pattern, string[, maxsplit=0, flags=0])<BR>split(string[, maxsplit=0])<BR>作用:可以将字符串匹配正则表达式的部分割开并返回一个列表<BR>例:简单分析ip</P> <P><div class="codetitle"><span><U></U></span> 代码如下:</p><div class="codebody" id="code62802"><BR>#!/usr/bin/env python<BR>import re<BR>r1 = re.compile('W+')<BR>print r1.split('192.168.1.1')<BR>print re.split('(W+)', '192.168.1.1')<BR>print re.split('(W+)', '192.168.1.1', 1) <BR></p><BR>结果如下:<BR>['192', '168', '1', '1']<BR>['192', '.', '168', '.', '1', '.', '1']<BR>['192', '.', '168.1.1']</P> <P>findall<BR>re.findall(pattern, string[, flags])<BR>findall(string[, pos[, endpos]])<BR>作用:在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回<BR>例:查找[]包括的内容(贪婪和非贪婪查找)</P> <P><div class="codetitle"><span><U></U></span> 代码如下:</p><div class="codebody" id="code45049"><BR>#!/usr/bin/env python<BR>import re<BR>r1 = re.compile('([.*])')<BR>print re.findall(r1, "hello[hi]heldfsdsf[iwonder]lo")<BR>r1 = re.compile('([.*?])')<BR>print re.findall(r1, "hello[hi]heldfsdsf[iwonder]lo")<BR>print re.findall('[0-9]{2}',"fdskfj1323jfkdj")<BR>print re.findall('([0-9][a-z])',"fdskfj1323jfkdj")<BR>print re.findall('(?=www)',"afdsfwwwfkdjfsdfsdwww")<BR>print re.findall('(?<=www)',"afdsfwwwfkdjfsdfsdwww") <BR></p></P> <P>finditer<BR>re.finditer(pattern, string[, flags])<BR>finditer(string[, pos[, endpos]])<BR>说明:和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并组成一个迭代器返回。同样 RegexObject 有:</P> <P>sub<BR>re.sub(pattern, repl, string[, count, flags])<BR>sub(repl, string[, count=0])<BR>说明:在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。Repl 既可以是字符串也可以是一个函数。<BR>例:</P> <P><div class="codetitle"><span><U></U></span> 代码如下:</p><div class="codebody" id="code71752"><BR>#!/usr/bin/env python<BR>import re<BR>p = re.compile('(one|two|three)')<BR>print p.sub('num', 'one word two words three words apple', 2) <BR></p></P> <P>subn<BR>re.subn(pattern, repl, string[, count, flags])<BR>subn(repl, string[, count=0])</P> <P>说明:该函数的功能和 sub() 相同,但它还返回新的字符串以及替换的次数。同样 RegexObject 有: </div> <div class=""> <ul class="m-news-opt fix"> <li class="opt-item"> <a href='/python-356850.html' target='_blank'><p>< 上一篇</p><p class="ellipsis">python将html转成PDF的实现代码(包含中文)</p></a> </li> <li class="opt-item ta-r"> <a href='/python-356852.html' target='_blank'><p>下一篇 ></p><p class="ellipsis">Python中条件选择和循环语句使用方法介绍</p></a> </li> </ul> </div> </div> </div> <div class="g-title fix"> <h2 class="title-txt">人气教程排行</h2> </div> <div class="m-rank u-dashed mb40"> <ul> <li class="rank-item"> <a href="/python-361871.html" title='对Python2.7pandas中的read_excel详解' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">384次</span> <span class="g-sort-num top">1</span> 对Python2.7pandas中的read_excel详解 </a> </li> <li class="rank-item"> <a href="/python-357851.html" title='Python实现定时弹窗提醒' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">383次</span> <span class="g-sort-num second">2</span> Python实现定时弹窗提醒 </a> </li> <li class="rank-item"> <a href="/python-359898.html" title='python爬虫入门(3)--利用requests构建知乎API' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">383次</span> <span class="g-sort-num third">3</span> python爬虫入门(3)--利用requests构建知乎API </a> </li> <li class="rank-item"> <a href="/python-361328.html" title='python如何爬取搜狗微信公众号文章永久链接的思路解析' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">382次</span> <span class="g-sort-num ">4</span> python如何爬取搜狗微信公众号文章永久链接的思路解析 </a> </li> <li class="rank-item"> <a href="/python-363639.html" title='python字典的键可以相同吗' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">381次</span> <span class="g-sort-num ">5</span> python字典的键可以相同吗 </a> </li> <li class="rank-item"> <a href="/python-462846.html" title='python是一种面向什么的语言?' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">381次</span> <span class="g-sort-num ">6</span> python是一种面向什么的语言? </a> </li> <li class="rank-item"> <a href="/python-355903.html" title='python通过pil为png图片填充上背景颜色的方法' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">381次</span> <span class="g-sort-num ">7</span> python通过pil为png图片填充上背景颜色的方法 </a> </li> <li class="rank-item"> <a href="/python-364233.html" title='python语言的编程模式有什么' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">380次</span> <span class="g-sort-num ">8</span> python语言的编程模式有什么 </a> </li> <li class="rank-item"> <a href="/python-353438.html" title='使用python获取进程pid号的方法' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">380次</span> <span class="g-sort-num ">9</span> 使用python获取进程pid号的方法 </a> </li> <li class="rank-item"> <a href="/python-362615.html" title='Python中如何解决无限循环的问题' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">380次</span> <span class="g-sort-num ">10</span> Python中如何解决无限循环的问题 </a> </li> <li class="rank-item"> <a href="/python-466149.html" title='怎么解决pip不是内部或外部命令' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">378次</span> <span class="g-sort-num ">11</span> 怎么解决pip不是内部或外部命令 </a> </li> <li class="rank-item"> <a href="/python-374795.html" title='python中def是什么意思' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">378次</span> <span class="g-sort-num ">12</span> python中def是什么意思 </a> </li> <li class="rank-item"> <a href="/python-361381.html" title='对numpy中数组元素的统一赋值实例' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">376次</span> <span class="g-sort-num ">13</span> 对numpy中数组元素的统一赋值实例 </a> </li> <li class="rank-item"> <a href="/python-378450.html" title='python的选择语句是什么语句' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">374次</span> <span class="g-sort-num ">14</span> python的选择语句是什么语句 </a> </li> <li class="rank-item"> <a href="/python-362375.html" title='Python中构造方法的解析(附示例)' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">374次</span> <span class="g-sort-num ">15</span> Python中构造方法的解析(附示例) </a> </li> <li class="rank-item"> <a href="/python-360729.html" title='关于python中引入导入与自定义模块以及外部文件的实例分享' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">373次</span> <span class="g-sort-num ">16</span> 关于python中引入导入与自定义模块以及外部文件的实例分享 </a> </li> <li class="rank-item"> <a href="/python-364421.html" title='python如何在不同类之间调用方法' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">372次</span> <span class="g-sort-num ">17</span> python如何在不同类之间调用方法 </a> </li> <li class="rank-item"> <a href="/python-462395.html" title='python中的【//】是什么运算符号' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">372次</span> <span class="g-sort-num ">18</span> python中的【//】是什么运算符号 </a> </li> <li class="rank-item"> <a href="/python-363743.html" title='python中╲t是什么' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">371次</span> <span class="g-sort-num ">19</span> python中╲t是什么 </a> </li> <li class="rank-item"> <a href="/python-357501.html" title='python同时给多个变量赋值' class="item-name ellipsis" target="_blank"> <span class="g-art-count fr">371次</span> <span class="g-sort-num ">20</span> python同时给多个变量赋值 </a> </li> </ul> </div> </div> </div> <!-- / 教程内容页 --> </div> </div> <!-- 页尾 --> <div class="footer"> 本站所有资源全部来源于网络,若本站发布的内容侵害到您的隐私或者利益,请联系我们删除!</div> <!-- / 页尾 --> <script type="text/javascript" src="/kan/js/read.js"></script> <div style="display:none"> <div class="login-box" id="login-dialog"> <div class="login-top"><a class="current" rel="nofollow" id="login1" onclick="setTab('login',1,2);" >登录</a></div> <div class="login-form" id="nav-signin"> <!-- <div class="login-ico"><a rel="nofollow" class="qq" id="qqlogin" target="_blank" href="/user-center-qqlogin.html"> QQ </a></div> --> <div class="login-box-form" id="con_login_1"> <form id="loginform" action="/user-center-login.html" method="post" onsubmit="return false;"> <p class="int-text"> <input class="email" id="username" name="username" type="text" value="用户名或Email" onfocus="if(this.value=='用户名或Email'){this.value='';}" onblur="if(this.value==''){this.value='用户名或Email';};" ></p> <p class="int-text"> <input class="password1" type="password" id="password" name="password" value="******" onBlur="if(this.value=='') this.value='******';" onFocus="if(this.value=='******') this.value='';" > </p> <p class="int-info"> <label class="ui-label"> </label> <label for="agreement" class="ui-label-checkbox"> <input type="checkbox" value="" name="cookietime" id="cookietime" checked="checked" value="2592000"> <input type="hidden" name="notforward" id="notforward" value="1"> <input type="hidden" name="dosubmit" id="dosubmit" value="1">记住我的登录 </label> <a rel="nofollow" class="aright" href="/user-center-forgetpwd.html" target="_blank"> 忘记密码? </a></p> <p class="int-btn"><a rel="nofollow" id="loginbt" class="loginbtn"><span>登录</span></a></p> </form> </div> <form id="regform" action="/user-center-reg.html" method="post"> <div class="login-reg" style="display: none;" id="con_login_2"> <input type="hidden" name="t" id="t"/> <p class="int-text"> <input id="email" name="email" type="text" value="Email" onfocus="if(this.value=='Email'){this.value='';}" onblur="if(this.value==''){this.value='Email';};"></p> <p class="int-text"> <input id="uname" name="username" type="text" value="用户名或昵称" onfocus="if(this.value=='用户名或昵称'){this.value='';}" onblur="if(this.value==''){this.value='用户名或昵称';};"></p> <p class="int-text"> <input type="password" id="pwd" name="password" value="******" onBlur="if(this.value=='') this.value='******';" onFocus="if(this.value=='******') this.value='';"> </p> <p class="int-text1"><span class="inputbox"> <input id="validate" name="validate" type="text" value="验证码" onfocus="if(this.value=='验证码'){this.value='';}" onblur="if(this.value==''){this.value='验证码';};"> </span><span class="yzm-img"><img src="/user-checkcode-index" alt="看不清楚换一张" id="indexlogin"></p> <p class="int-info"> <label> <input value="" name="agreement" id="agreement" CHECKED="checked" type="checkbox"> 我已阅读<a rel="nofollow" href="/user-center-agreement.html">用户协议</a>及<a rel="nofollow" href="/user-center-agreement.html">版权声明</a></label> </p> <p class="int-btn"><input type="hidden" name="dosubmit"/> <a rel="nofollow" class="loginbtn" id="register"><span>注册</span></a></p> </div> </form> </div> </div> </div> </div> <script type="text/javascript" src="/kan/js/foot_js.js"></script> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?6dc1c3c5281cf70f49bc0bc860ec24f2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <script type="text/javascript" src="/layui/layui.js"></script> <script> layui.use('code', function() { layui.code({ elem: 'pre', //默认值为.layui-code about: false, skin: 'notepad', title: 'php怎么实现数据库验证跳转代码块', encode: true //是否转义html标签。默认不开启 }); }); </script> </body> </html>