python re正则表达式模块(Regular Expression)
模块的的作用主要是用于字符串和文本处理,查找,搜索,替换等
复习一下基本的正则表达式吧
.:匹配除了换行符以为的任意单个字符
*:匹配任意字符,一个,零个,多个都能匹配得到俗称贪婪模式
+:匹配位于+之前的一个或者多个字符
|:匹配位于|之前或者之后的字符
^:匹配行首
$:匹配行尾
?:匹配位于?之前的零个或者一个字符,不匹配多个字符
\:表示\之后的为转义字符
[]:匹配[]之中的任意单个字符,[0-9]表示匹配0到9任意一个数字
():将位于()之内的的内容当作一个整体
{}:按{}中的次数进行匹配,100[0-9]{3}表示在100之后任意匹配一个3位数(100-999)
python中以\开头的元字符:
正则表达式语法表
匹配的标志和含义
文本内容(提取Linux下的password文件)
man:x:6:12:man:/var/cache/man:/bin/nologin
re模块中有3个搜索函数,每个函数都接受3个参数(匹配模式,要匹配的字符串,进行匹配的标志),如果匹配到了就返回一个对象实例,么有就返会None.
findall():用于在字符串中查找符合正则表达式的字符串,并返回这些字符串的列表
search():搜索整个字符串,返回对象实例
match():只从第一个字符开始匹配,后面的不再匹配,返回对象实例
lovelinux@LoveLinux:~/py/boke$cattext man:x:6:12:man:/var/cache/man:/bin/sh lovelinux@LoveLinux:~/py/boke$cattest.py #/usr/bin/envpython #coding:utf-8 importre withopen('text','r')astxt: f=txt.read() printre.match('bin',f) printre.search('bin',f).end() lovelinux@LoveLinux:~/py/boke$pythontest.py None 34 lovelinux@LoveLinux:~/py/boke$vimtest.py lovelinux@LoveLinux:~/py/boke$pythontest.py None <_sre.SRE_Matchobjectat0x7f12fc9f9ed0>
返回是对象实例有2个方法,
start():返回记录匹配到字符的开始索引
end():返回记录匹配到字符的结束索引
lovelinux@LoveLinux:~/py/boke$pythontest.py None 31 34 lovelinux@LoveLinux:~/py/boke$cattest.py #/usr/bin/envpython #coding:utf-8 importre withopen('text','r')astxt: f=txt.read() printre.match('bin',f) printre.search('bin',f).start() printre.search('bin',f).end()