码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习-37.Python中的正则表达式

时间:2014-09-30 00:03:31      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   sp   div   c   on   log   

作为一门现代语言,正则表达式是必不可缺的,在Python中,正则表达式位于re模块。

1 import re

这里不说正则表达式怎样去匹配,例如\d代表数字,^代表开头(也代表非,例如^a-z则不匹配任何小写字符),$代表结尾,这些百科或者其他书籍都有。

例子一,字符串中是否包含数字:

1 import re
2 userinput = input("please input test string:")
3 if re.match(r\d,userinput):
4     print(contain number)
5 else:
6     print(no number in input string)

假如输入的不包含数字的话,则re.match方法返回None,而含数字的话,则会返回一个Match对象。

 

例子二,分割字符串:

1 import re
2 userinput = input("please input test string:")
3 temp = re.split(r\s+,userinput)
4 print(temp)

\s代表任意空白字符(指空格、Tab等等的空白字符),+号表示1个或多个。那么这段代码的作用就是按照空白分割字符。例如字符串"a   b       dc"得到的将会是[‘a‘,‘b‘,‘dc‘]的列表。普通的字符串split函数要做到此功能则很难做到。

 

例子三,分组:

有时候,我们需要提取字符串中的一些部分,例如电话号码,由三位或四位的区号和八位的电话号码组成。

1 import re
2 userinput = input("please input test string:")
3 m = re.match(r(\d{3,4})-(\d{8}),userinput)
4 if m:
5     print(区号: + m.group(1))
6     print(号码: + m.group(2))
7 else:
8     print(格式错误)

分组使用(),这是正则表达式的基本。m.group从0开始计数,而0为输入的字符串。

 

例子四,贪婪匹配:

1 import re
2 userinput = input("please input test string:")
3 m = re.match(r^(\d+)(0*)$,userinput)
4 if m:
5     print(m.groups())
6 else:
7     print(格式错误)

输入102500,我们得到的是(‘102500‘,‘‘)。

而我们想要的结果是(‘1025‘,‘00‘)。这里就需要使用非贪婪匹配了。因为Python里正则表达式是默认使用贪婪模式的(C#中也是)。

修改代码如下:

1 import re
2 userinput = input("please input test string:")
3 m = re.match(r^(\d+?)(0*)$,userinput)
4 if m:
5     print(m.groups())
6 else:
7     print(格式错误)

即在\d+后加上一个?号。这样结果就会如我们所想的一样。

注意的是,非贪婪模式比贪婪模式效率要差,因此非到贪婪模式匹配不了就不要使用非贪婪模式。

 

例子五,正则表达式预编译:

使用re.compile方法。在多处需要使用到同一个正则表达式的时候,我们应该预编译该正则表达式,然后直接使用该方法返回的对象。

Python学习-37.Python中的正则表达式

标签:style   blog   color   使用   sp   div   c   on   log   

原文地址:http://www.cnblogs.com/h82258652/p/4000970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!