re模块

什么是正则表达式

正则表达式,英文叫做Regular Expression。简单说,正则表达式就是一组规则,用于实现字符串的查找,匹配,以实现关于字符串的相关操作,比如替换,删除等。

正则表达式分为基本正则表达式(BRE),扩展正则表达式(ERE)两类。

什么是Python的正则表达式

Python中的正则表达式模块就是re模块,在Python中可以通过re模块来做正则表达式的操作。

Python中re模块的常用方法有:match,search,findall,sub,replace,split等

常用的匹配规则有:

##字符匹配:
.     #匹配除换行符以外的任意字符
\w    #匹配字母或数字或下划线或汉字
\s    #匹配任意的空白符
\d    #匹配数字
\b    #匹配单词的开始或结束
^     #匹配字符串的开始
$     #匹配字符串的结束

##次数匹配:
*     #重复零次或更多次
+     #重复一次或更多次
?     #重复零次或一次
{n}   #重复n次
{n,}  #重复n次或更多次
{n,m} #重复n到m次

下面将通过实例对re模块的常用方法做说明

1、match(pattern, string, flags=0)

从起始位置开始根据模型去字符串中匹配指定内容,匹配单个

  • 正则表达式
  • 要匹配的字符串
  • 标志位,用于控制正则表达式的匹配方式
import re

obj = re.match('\d+', '123uuasf')
if obj:
    print obj.group()
# flags
I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments

2、search(pattern, string, flags=0)

根据模型去字符串中匹配指定内容,匹配单个

import re

obj = re.search('\d+', 'u123uu888asf')
if obj:
    print obj.group()

3、group和groups

a = "123abc456"
print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group()

print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0)
print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1)
print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2)

print re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()

4、findall(pattern, string, flags=0)

上述两中方式均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall。

import re

obj = re.findall('\d+', 'fa123uu888asf')
print obj

5、sub(pattern, repl, string, count=0, flags=0)

用于替换匹配的字符串

content = "123abc456"
new_content = re.sub('\d+', 'sb', content)
# new_content = re.sub('\d+', 'sb', content, 1)
print new_content

相比于str.replace功能更加强大

6、split(pattern, string, maxsplit=0, flags=0)

根据指定匹配进行分组

content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"
new_content = re.split('\*', content)
# new_content = re.split('\*', content, 1)
print new_content
content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"
new_content = re.split('[\+\-\*\/]+', content)
# new_content = re.split('\*', content, 1)
print new_content
inpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))'
inpp = re.sub('\s*','',inpp)
new_content = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)', inpp, 1)
print new_content

相比于str.split更加强大

匹配IP地址:

^([-]|[-]\d|[-]?\d?\d)(\.([-]|[-]\d|[-]?\d?\d)){}$

匹配手机号:

^[|||][-]\d{}$

参考链接:

http://www.crifan.com/files/doc/docbook/python_topic_re/release/html/python_topic_re.html

http://www.cnblogs.com/wupeiqi/articles/4963027.html

My way to Python - Day04 - 模块的更多相关文章

  1. Python标准模块--threading

    1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...

  2. Python的模块引用和查找路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于“模块”这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译型的语言,比如C#中 ...

  3. Python Logging模块的简单使用

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  4. Python标准模块--logging

    1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...

  5. python基础-模块

    一.模块介绍                                                                                              ...

  6. python 安装模块

    python安装模块的方法很多,在此仅介绍一种,不需要安装其他附带的pip等,python安装完之后,配置环境变量,我由于中英文分号原因,环境变量始终没能配置成功汗. 1:下载模块的压缩文件解压到任意 ...

  7. python Queue模块

    先看一个很简单的例子 #coding:utf8 import Queue #queue是队列的意思 q=Queue.Queue(maxsize=10) #创建一个queue对象 for i in ra ...

  8. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  9. Python引用模块和查找模块路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于"模块"这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译 ...

随机推荐

  1. 用MVC4练习,后台用aspx,数据库DemoDb《MvcUserDemo》

    将ado.net的cs文件SqlHelper.cs放入解决方案 using System; using System.Collections.Generic; using System.Linq; u ...

  2. html5.边框属性相关知识点

    border-left 定义左边框 border-top 定义上边框 border-right 定义有边框 border-bottom 定义下边框 边框样式: dotted 边框线为点状虚线 dash ...

  3. hdu 2101

    #include <stdio.h> int main() { int a,b; while(scanf("%d%d",&a,&b)!=EOF) { i ...

  4. 使用VS Code开发Angular 2应用程序所需配置文件的解析

    目录 package.json typings.json tsconfig.json launch.json settings.json tasks.json package.json: 这是项目的基 ...

  5. redis cluster 集群搭建步骤和注意事项

    1.安装Ubuntu ,修改root的密码. sudo passwd  (apt-get update 更新系统) 2.安装 Gcc 和G++  sudo apt-get install build- ...

  6. Canvas--2

    Canvas2(关键词:setLineDash .rect .strokeRect .clearRect .arc.sin .strokeText )   绘制其他样式: lineCap 结束端点的设 ...

  7. HTML常见标签学习与笔记总结

    HTML其实就是把页面的数据封装并加上标签 表头<head> <title> 浏览器标题栏显示的内容 <base> 有href和target属性,href指定网页中 ...

  8. uva 759 - The Return of the Roman Empire

    #include <cstdio> #include <string> #include <map> using namespace std; ; , , , , ...

  9. hdu 2019

    Problem Description 有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序.   Input 输入数据包含多 ...

  10. cf C. Vasya and Robot

    http://codeforces.com/contest/355/problem/C 枚举L和R相交的位置. #include <cstdio> #include <cstring ...