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

Python 深入正则表达式

时间:2016-02-27 19:20:32      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

#!/usr/bin/env python3
import re

‘‘‘
#常用功能介绍

[Pp]ython 匹配 "Python" 或 "python"
rub[ye] 匹配 "ruby" 或 "rube"
[aeiou] 匹配中括号内的任意一个字母
[0-9] 匹配任何数字。类似于 [0123456789]
[a-z] 匹配任何小写字母
[A-Z] 匹配任何大写字母
[a-zA-Z0-9] 匹配任何字母及数字
[^aeiou] 除了aeiou字母以外的所有字符
[^0-9] 匹配除了数字外的字符

. 匹配除 "\n" 之外的任何单个字符。要匹配包括 ‘\n‘ 在内的任何字符,请使用象 ‘[.\n]‘ 的模式。
\d 匹配一个数字字符。等价于 [0-9]。
\D 匹配一个非数字字符。等价于 [^0-9]。
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
\S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。
\w 匹配包括下划线的任何单词字符。等价于‘[A-Za-z0-9_]‘。
\W 匹配任何非单词字符。等价于 ‘[^A-Za-z0-9_]‘。
‘‘‘



strings = ‘1k3jksl24kljzdio43ndsfoi4nsadf‘

#re.compile() : complie()先将需要匹配的对象进行编译,好处是 提高执行速度

re_complie=re.compile("[0-9]+")


#match 从整个对象的开头开始匹配,返回的类型是字符串
sb = re_complie.match(strings)
print(sb.group())

#search 在整个对象中查找,找到第一个就返回值,返回的类型是字符串
sb = re_complie.search(strings)
print(sb.group())

#findall 在整个对象中查找,返回一个列表
sb = re_complie.findall(strings)
print(sb)


#re.split(): split()用户分割对象
#split 将匹配到的格式当做分割点对字符串分割成列表
sb = re_complie.split(strings)
print(sb)


#sub 替换匹配到的字符
#count 指定替换多少个;例如本例中找到5个元素,指定替换四个元素
sb = re_complie.sub("|",strings,count=4)
print(sb)


#实例1: 匹配手机号

phone_number = ‘my name is andy , my phone number is 13162156638 , your call me andy‘
p_number= re.search("(1)[3458][0-9]{9}",phone_number) #方法一
p_number= re.search("(1)[3458]\d{9}",phone_number) #方法二
print(p_number)


#实例2: 匹配IP地址
ipaddress = "inet 192.168.60.223 netmask 0xffffff00 broadcast 192.168.60.255"
ip = re.search("(\d{3}.){2}(\d{1,3}.){2}",ipaddress) #方法一
ip = re.search("(\d{1,3}.){4}",ipaddress) #方法二
print(ip.group())


#实例3: 分组匹配

message = ‘Oldboy School, Beijing Changping Shahe: 010-8343245‘
match = re.search(r‘(\w+) (\w+) (\S+)‘,message)

print(match.group())

#实例3: 匹配email地址

message = ‘andy@163.com http://blog.163.com‘
emails = "alex.li@126.com http://www.oldboyedu.com"

email = re.search("[a-zA-z0-9]+@[0-9]+\.com",message)
m = re.search(r"[0-9.a-z]{0,26}@[0-9.a-z]{0,20}.[0-9a-z]{0,8}", emails)
print(email.group())
print(m.group())

Python 深入正则表达式

标签:

原文地址:http://www.cnblogs.com/RainBower/p/5223303.html

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