参考资料:http://deerchao.net/tutorials/regex/regex.htm

1、正则表达式基础

2、python 正则表达式

1、正则表达式基础

元字符:

其他语法:

(1)字符转义

如果你想查找元字符本身的话,比如你查找.,或者*,就出现了问题:你没办法指定它们,因为它们会被解释成别的意思。这时你就得使用\来取消这些字符的特殊意义。因此,你应该使用\.和\*。当然,要查找\本身,你也得用\\.

例如C:\\Windows 匹配C:\Windows

(2)分组——用小括号来指定子表达式(也叫做分组)

例如:(\d{1,3}\.){3}\d{1,3}是一个简单的IP地址匹配表达式,\d{1,3}匹配1到3位的数字,(\d{1,3}\.){3}匹配三位数字加上一个英文句号(这个整体也就是这个分组)重复3次,最后再加上一个一到三位的数字(\d{1,3})。不幸的是,它也将匹配256.300.888.999这种不可能存在的IP地址。选择,字符类来描述一个正确的IP地址为:((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)。

(3)贪婪与懒惰

当正则表达式中包含能接受重复的限定符时,通常的行为是(在使整个表达式能得到匹配的前提下)匹配尽可能多的字符。以这个表达式为例:a.*b,它将会匹配最长的以a开始,以b结束的字符串。如果用它来搜索aabab的话,它会匹配整个字符串aabab。这被称为贪婪匹配。

有时,我们更需要懒惰匹配,也就是匹配尽可能少的字符。前面给出的限定符都可以被转化为懒惰匹配模式,只要在它后面加上一个问号?。这样.*?就意味着匹配任意数量的重复,但是在能使整个匹配成功的前提下使用最少的重复。现在看看懒惰版的例子吧:a.*?b匹配最短的,以a开始,以b结束的字符串。如果把它应用于aabab的话,它会匹配aab(第一到第三个字符)和ab(第四到第五个字符)。

2、python正则表达式

实例:1:(search和match与sub)

# encoding:utf-8
'''
Created on 2014-6-18 @author: Administrator
'''
import re class Regex(object):
def regex_match(self):
pattern = "\w+@\w+.*(\w+)\.com" # 匹配邮箱
mt = re.match(pattern, "luosongchao@xxx.yyy.xadad.com")
if mt:
print mt.group()
print mt.groups()
else:
print "no match" def regex_search(self):
mt = re.search(r"\Bl(.?){2}", "hello world!")
if mt:
print mt.group()
else:
print "no match" def regex_sub(self):
ret = re.sub("X", "Mr Smith", "attention:X\n\nDear X,\n")
print ret
ret = re.subn("X", "Mr Smith", "attention:X\n\nDear X,\n")
print ret if __name__ == "__main__":
regex = Regex()
regex.regex_match()
regex.regex_search()
regex.regex_sub()

结果:

结论:

match:从字符串开头开始对模式进行匹配,成功返回匹配对象,否则返回None

search:在字符串string中搜索正则表达式模式pattern第一次出现的字符串

sub:把字符串中匹配正则表达式pattern的地方替换为新字符串

实例2:(split)

# encoding:utf-8
'''
Created on 2014-6-18 @author: Administrator
''' import re
class RegexLs(object):
"""使用正则表达式解析Unix命令ls -al的结果""" def __init__(self, path):
try:
self.fl = open(path)
except Exception :
print "文件" + path + "打开出错!" def analy_file(self):
pattern = "\s+|\t"
for line in self.fl:
print re.split(pattern, line.strip()) def __del__(self):
self.fl.close() if __name__ == "__main__":
path = "ls.txt"
regex_ls = RegexLs(path)
regex_ls.analy_file()

其中Unix命令:ls –al    生成结果格式:

结论:

split,根据正则表达式pattern中的分隔符把字符串string分隔为一个列表

实例3:(惰性匹配)

# encoding:utf-8
'''
Created on 2014-6-18 @author: Administrator
'''
from random import randint, choice
from sys import maxint
from time import ctime
from string import lowercase
import re class RegexExample(object):
def __init__(self):
self.doms = ('com', 'edu', 'net', 'org', 'gov')
self.format_list = [] def get_string(self):
for i in range(randint(5, 10)):
dtint = randint(0, maxint - 1)
dtstr = ctime(dtint)
shorter = randint(4, 7) em = ""
for j in range(shorter):
em += choice(lowercase) longer = randint(shorter, 12)
dn = ""
for j in range(longer):
dn += choice(lowercase) string = "%s::%s@%s.%s::%d-%d-%d" % (dtstr, em, dn, choice(self.doms), dtint, shorter, longer)
# print string
self.format_list.append(string) def get_last(self):
pattern = ".+?(\d+-\d+-\d+)"
for elem in self.format_list:
print elem
ps = re.search(pattern, elem)
if ps:
print ps.group(1) if __name__ == "__main__":
example = RegexExample()
example.get_string() print "#"*40 example.get_last()

执行结果:

结论:

get_last()函数使用的pattern=”.*?(\d-\d-\d)”执行的是惰性匹配,其中(\d-\d-\d)为分组

【python】正则表达式的更多相关文章

  1. Python 正则表达式入门(中级篇)

    Python 正则表达式入门(中级篇) 初级篇链接:http://www.cnblogs.com/chuxiuhong/p/5885073.html 上一篇我们说在这一篇里,我们会介绍子表达式,向前向 ...

  2. Python正则表达式中的re.S

    title: Python正则表达式中的re.S date: 2014-12-21 09:55:54 categories: [Python] tags: [正则表达式,python] --- 在Py ...

  3. Python 正则表达式入门(初级篇)

    Python 正则表达式入门(初级篇) 本文主要为没有使用正则表达式经验的新手入门所写. 转载请写明出处 引子 首先说 正则表达式是什么? 正则表达式,又称正规表示式.正规表示法.正规表达式.规则表达 ...

  4. python正则表达式re

    Python正则表达式: re 正则表达式的元字符有. ^ $ * ? { [ ] | ( ).表示任意字符[]用来匹配一个指定的字符类别,所谓的字符类别就是你想匹配的一个字符集,对于字符集中的字符可 ...

  5. Python正则表达式详解

    我用双手成就你的梦想 python正则表达式 ^ 匹配开始 $ 匹配行尾 . 匹配出换行符以外的任何单个字符,使用-m选项允许其匹配换行符也是如此 [...] 匹配括号内任何当个字符(也有或的意思) ...

  6. 比较详细Python正则表达式操作指南(re使用)

    比较详细Python正则表达式操作指南(re使用) Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式.Python 1.5之前版本则是通过 regex 模块提供 E ...

  7. Python正则表达式学习摘要及资料

    摘要 在正则表达式中,如果直接给出字符,就是精确匹配. {m,n}? 对于前一个字符重复 m 到 n 次,并且取尽可能少的情况 在字符串'aaaaaa'中,a{2,4} 会匹配 4 个 a,但 a{2 ...

  8. python正则表达式 小例几则

    会用到的语法 正则字符 释义 举例 + 前面元素至少出现一次 ab+:ab.abbbb 等 * 前面元素出现0次或多次 ab*:a.ab.abb 等 ? 匹配前面的一次或0次 Ab?: A.Ab 等 ...

  9. Python 正则表达式-OK

    Python正则表达式入门 一. 正则表达式基础 1.1. 简单介绍 正则表达式并不是Python的一部分. 正则表达式是用于处理字符串的强大工具, 拥有自己独特的语法以及一个独立的处理引擎, 效率上 ...

  10. Python天天美味(15) - Python正则表达式操作指南(re使用)(转)

    http://www.cnblogs.com/coderzh/archive/2008/05/06/1185755.html 简介 Python 自1.5版本起增加了re 模块,它提供 Perl 风格 ...

随机推荐

  1. vs C#数据库导入EXCLE

    using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...

  2. SQL SERVER中查询参数为空(null)时默认查询所有的实现

    最近在项目中碰到一个比较有意思的问题,网上查找了一些方法,在这里总结分享一下. 我们经常会碰到这样的场景:需要查询数据,有一些查询条件,但是查询的时候,我们希望在某个条件为空的时候,则不筛选这个条件, ...

  3. 封装document.ready方法

    function $(fn){ if(document.addEventListener){ //W3C document.addEventListener('DOMContentLoaded',fu ...

  4. lua进阶(二)

    第五章 函数 函数有两种用途:1.完成指定的任务,这种情况下函数作为调用语句使用:2.计算并    返回值,这种情况下函数作为赋值语句的表达式使用. function function_name( . ...

  5. System.Transaction (TransactionScope) 与 可提升 (Promotable) 交易

    这是我的备份,原文请看  http://www.dotblogs.com.tw/mis2000lab/archive/2014/11/12/transactionscope_promotable_tr ...

  6. 一幅图证明chrome的由来和目的

  7. DTAP street

    一个网站程序的上线一般要经过开发[Development]测试[Testing]验收[Acceptance]生产[Production].所以又叫做DTAP street.对应有开发环境.测试环境.验 ...

  8. C#调用sap接口及返回数据到sap

    public class SapClass { /// <summary> /// /// </summary> /// <param name="fphm&q ...

  9. About Inside the Azure Storage Outage of November 18th

    Channel 9的官方解释 http://channel9.msdn.com/posts/Inside-the-Azure-Storage-Outage-of-November-18th 曾经在自己 ...

  10. throw和throws

    uncheckException的处理 class User{ private int age; public void setAge(int age){ if(age < 0){ //生成异常 ...