您好,欢迎来到赴品旅游。
搜索
您的当前位置:首页python的正则表达式re模块的常用方法

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

来源:赴品旅游

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

代码如下:


import re
print re.__doc__

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

2.re的正则表达式语法

正则表达式语法表如下:

语法 意义 说明
"." 任意字符
"^" 字符串开始 '^hello'匹配'helloworld'而不匹配'aaaahellobbb'
"$" 字符串结尾 与上同理
"*"
0 个或多个字符(贪婪匹配)
<*>匹配chinaunix
"+"
1 个或多个字符(贪婪匹配)
与上同理
"?"
0 个或多个字符(贪婪匹配)
与上同理
*?,+?,??
以上三个取第一个匹配结果(非贪婪匹配) <*>匹配<BR></TD></TR> <TR> <TD>{m,n}<BR></TD> <TD>对于前一个字符重复m到n次,{m}亦可<BR></TD> <TD>a{6}匹配6个a、a{2,4}匹配2到4个a </TD></TR> <TR> <TD>{m,n}?<BR></TD> <TD>对于前一个字符重复m到n次,并取尽可能少<BR></TD> <TD>‘aaaaaa'中a{2,4}只会匹配2个 </TD></TR> <TR> <TD>"\\"<BR></TD> <TD>特殊字符转义或者特殊序列 </TD> <TD><BR></TD></TR> <TR> <TD>[]<BR></TD> <TD>表示一个字符集 </TD> <TD>[0-9]、[a-z]、[A-Z]、[^0] </TD></TR> <TR> <TD>"|"<BR></TD> <TD>或 </TD> <TD>A|B,或运算 </TD></TR> <TR> <TD>(...)<BR></TD> <TD>匹配括号中任意表达式 </TD> <TD><BR></TD></TR> <TR> <TD>(?#...)<BR></TD> <TD>注释,可忽略 </TD> <TD><BR></TD></TR> <TR> <TD>(?=...)<BR></TD> <TD>Matches if ... matches next, but doesn't consume the string.<BR></TD> <TD>'(?=test)' 在hellotest中匹配hello </TD></TR> <TR> <TD>(?!...)<BR></TD> <TD>Matches if ... doesn't match next.<BR></TD> <TD>'(?!=test)' 若hello后面不为test,匹配hello<BR></TD></TR> <TR> <TD>(?<=...) <BR></TD> <TD>Matches if preceded by ... (must be fixed length).<BR></TD> <TD>'(?<=hello)test' 在hellotest中匹配test<BR></TD></TR> <TR> <TD>(?</TD> <TD>Matches if not preceded by ... (must be fixed length).<BR></TD> <TD>'(?</TD></TR></TBODY></TABLE><BR>正则表达式特殊序列表如下: <p> <TABLE style="WIDTH: 60%" borderColor=#000000 cellSpacing=0 cellPadding=2 border=1> <TBODY> <TR> <TD>特殊序列符号<BR></TD> <TD>意义 </TD></TR> <TR> <TD>\A<BR></TD> <TD>只在字符串开始进行匹配 </TD></TR> <TR> <TD>\Z<BR></TD> <TD>只在字符串结尾进行匹配 </TD></TR> <TR> <TD>\b<BR></TD> <TD>匹配位于开始或结尾的空字符串 </TD></TR> <TR> <TD>\B<BR></TD> <TD>匹配不位于开始或结尾的空字符串 </TD></TR> <TR> <TD>\d<BR></TD> <TD>相当于[0-9] </TD></TR> <TR> <TD>\D<BR></TD> <TD>相当于[^0-9] </TD></TR> <TR> <TD>\s<BR></TD> <TD>匹配任意空白字符:[\t\n\r\r\v] </TD></TR> <TR> <TD>\S<BR></TD> <TD>匹配任意非空白字符:[^\t\n\r\r\v] </TD></TR> <TR> <TD>\w<BR></TD> <TD>匹配任意数字和字母:[a-zA-Z0-9] </TD></TR> <TR> <TD>\W<BR></TD> <TD>匹配任意非数字和字母:[^a-zA-Z0-9] </TD></TR></TBODY></TABLE><BR> <P>3.re的主要功能函数</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>下面是几个例子:<BR>例:最基本的用法,通过re.RegexObject对象调用</P> <P> 代码如下:</p><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> 代码如下:</p><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> 代码如下:</p><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> 代码如下:</p><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> 代码如下:</p><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> 代码如下:</p><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 有: <script type="text/javascript" src="https://jss.huatuo6.com/pc/wenzhang/detail_dy.js"></script> <script type="text/javascript" src="https://jss.fupindai.com/pc/wenzhang/detail_left.js"></script> </div> <div class="glfra_f"> </div> </div> <script type="text/javascript" src="https://jss.fupindai.com/pc/wenzhang/wenzhang/detail_foot.js"></script> <script type="text/javascript" src="https://jss.fupindai.com/pc/share_right_gg1.js"></script> <script type="text/javascript" src="https://jss.huatuo6.com/pc/share_right_xgzx.js"></script> <script type="text/javascript" src="https://jss.fupindai.com/pc/share_right_gg2.js"></script> <script type="text/javascript" src="https://jss.huatuo6.com/pc/share_right_rmyd.js"></script> </div> <div class="n_right"> <script type="text/javascript" src="https://jss.fupindai.com/pc/share_cebian_gg1.js"></script> <script type="text/javascript" src="https://jss.huatuo6.com/pc/share_cebian_rmht.js"></script> <script type="text/javascript" src="https://jss.fupindai.com/pc/share_cebian_gg2.js"></script> <script type="text/javascript" src="https://jss.huatuo6.com/pc/share_cebian_rmtw.js"></script> <script type="text/javascript" src="https://jss.fupindai.com/pc/share_cebian_gg3.js"></script> <script type="text/javascript" src="https://jss.huatuo6.com/pc/share_cebian_wntj.js"></script> </div> </div> <script type="text/javascript" src="https://jss.huatuo6.com/pc/tj_foot1.js"></script><div class="foot"> <div class="smain"> <div class="foot_ano clearfix"> <!-- <div class="foot_logo"> <img src="images/logo_w.png" alt="AI游中国" /> </div> --> <div class="foot_mesg"> <p> Copyright © 2019-<span class="currentYear"></span> fupindai.com 版权所有 <a href="https://beian.miit.gov.cn/" target="_blank" style="color:#fff">赣ICP备2024042792号-2</a> </p> <p> 违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com </p> <p> 本站由北京市万商天勤律师事务所王兴未律师提供法律服务 </p> </div> </div> </div> </div> <script type="text/javascript"> const currentYear = new Date().getFullYear(); $('.currentYear').html(currentYear) </script>