您的位置:首页 > 编程语言 > Python开发

Python标准库中的re模块

2018-03-31 20:59 281 查看

      Python  的  re  模块(Regular  Expression  正则表达式)提供各种正则表达式的匹配操作,在文本解析、复杂字符串分析和信息提取时是一个非常有用的工具。

        正则表达式语法表如下:
语法意义说明
"."匹配除“\n”之外的任何单个字符  
"^"字符串开始'^hello'匹配'helloworld'而不匹配'aaaahellobbb'
"$"字符串结尾'world$'匹配'helloworld'而不匹配'worldobbb'
"*"匹配前面的子表达式任意次(贪婪匹配)zo*能匹配“z”,也能匹配“zo”以及“zoo”。*等价于o{0,}
"+"匹配前面的子表达式一次或多次(大于等于1次)(贪婪匹配)“zo+”能匹配“zo”以及“zoo”,但不能匹配“z”。+等价于{1,}
"?"匹配前面的子表达式零次或一次(贪婪匹配)“do(es)?”可以匹配“do”或“does”中的“do”。?等价于{0,1}
*?,  ?,??尽可能少的匹配所搜索的字符串(非贪婪匹配)对于字符串“oooo”,“o+”将尽可能多的匹配“o”,得到结果[“oooo”],而“o+?”将尽可能少的匹配“o”,得到结果['o',    'o',    'o',    'o']
{m,n}m和n均为非负整数,其中n<=m。最少匹配n次且最多匹配m次a{6}匹配6个a、a{2,4}匹配2到4个a
{m,n}?对于前一个字符重复m到n次,并取尽可能少‘aaaaaa’中a{2,4}只会匹配2个
"\\"特殊字符转义或者特殊序列 
  

[]
表示一个字符集[0-9]、[a-z]、[A-Z]、[^0]
"|"A|B,或运算
(...)匹配括号中任意表达式 
  

(?#...)
注释,可忽略 
(?=...)非获取匹配,正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用'(?=test)'    在hellotest中匹配hello
(?!...)  非获取匹配,正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用'(?!=test)'    若hello后面不为test,匹配hello
(?  <  =...)非获取匹配,反向肯定预查,与正向肯定预查类似,只是方向相反。'(?  <  =hello)test'    在hellotest中匹配test
(?  <  !...)非获取匹配,反向否定预查,与正向否定预查类似,只是方向相反。'(?  <  !hello)test'    在hellotest中不匹配test
        正则表达式特殊序列表如下:

特殊序列符号      意义

\A                        只在字符串开始进行匹配

\Z                        只在字符串结尾进行匹配

\b                        匹配位于开始或结尾的空字符串

\B                        匹配不位于开始或结尾的空字符串

\d                        相当于[0-9]

\D                        相当于[^0-9]

\s                        匹配任意空白字符:[\t\n\r\r\v]

\S                        匹配任意非空白字符:[^\t\n\r\r\v]

\w                        匹配任意数字和字母:[a-zA-Z0-9]

\W                        匹配任意非数字和字母:[^a-zA-Z0-9]

re的主要功能函数

        常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)

compile

        re.compile(pattern[,  flags])

        作用:把正则表达式语法转化成正则表达式对象

            flags定义包括:

                re.I:忽略大小写

                re.L:表示特殊字符集  \w,  \W,  \b,  \B,  \s,  \S  依赖于当前环境

                re.M:多行模式

                re.S:’  .  ’并且包括换行符在内的任意字符(注意:’  .  ’不包括换行符)

                re.U:  表示特殊字符集  \w,  \W,  \b,  \B,  \d,  \D,  \s,  \S  依赖于  Unicode  字符属性数据库

search

        re.search(pattern,  string[,  flags])

        search  (string[,  pos[,  endpos]])

        作用:在字符串中查找匹配正则表达式模式的位置,返回  MatchObject  的实例,如果没有找到匹配的位置,则返回  None。

match

        re.match(pattern,  string[,  flags])

        match(string[,  pos[,  endpos]])

        作用:match()  函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置  0  开始的匹配情况,而  search()  函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用  search()。

        下面是几个例子:

        例:最基本的用法
>>>  import  re

>>>  r1  =  re.compile(r'world')

>>>  print(r1.match('helloworld'))

None

>>>  print(r1.search('helloworld'))

<_sre.SRE_Match  object;  span=(5,  10),  match='world'>

>>>  
        r是raw(原始)的意思。因为在表示字符串中有一些转义符,如表示回车'\n'。如果要表示\表需要写为'\\'。但如果我就是需要表示一个'\'+'n',不用r方式要写为:'\\n'。但使用r方式则为r'\n'这样清晰多了。

        例:设置flag
>>>  r2  =  re.compile(r'n$',  re.S)

>>>  print(r2.search('helloworld'))

None

>>>  r2  =  re.compile('\n$',  re.S)

>>>  print(r2.search('helloworld'))

None

>>>  r2  =  re.compile(r'd$',  re.S)

>>>  print(r2.search('helloworld'))

<_sre.SRE_Match  object;  span=(9,  10),  match='d'>

>>>  r2  =  re.compile('World$',  re.I)

>>>  print(r2.search('helloworld'))

<_sre.SRE_Match  object;  span=(5,  10),  match='world'>

>>>  r2  =  re.compile(r'n$',  re.S)

>>>  print(r2.search('helloworld\n'))

None

>>>  r2  =  re.compile('\n$',  re.S)

>>>  print(r2.search('helloworld\n'))

<_sre.SRE_Match  object;  span=(10,  11),  match='\n'>

>>>  r2  =  re.compile('World$',  re.I)

>>>  print(r2.search('helloworld\n'))

<_sre.SRE_
4000
Match  object;  span=(5,  10),  match='world'>

>>>  
        例:直接调用
>>>  print(re.search(r'abc','helloaaabcdworldn'))

<_sre.SRE_Match  object;  span=(7,  10),  match='abc'>
split

        re.split(pattern,  string[,  maxsplit=0,  flags=0])

        split(string[,  maxsplit=0])

        作用:可以将字符串匹配正则表达式的部分割开并返回一个列表

        例:简单分析ip
>>>  print  (re.split('(\W+)','192.168.1.1',1))

['192',  '.',  '168.1.1']

>>>  print  (re.split('(\W+)','192.168.1.1'))

['192',  '.',  '168',  '.',  '1',  '.',  '1']

>>>  r1  =  re.compile('\W+')

>>>  print  (r1.split('192.168.1.1'))

['192',  '168',  '1',  '1']

>>>  
findall

        re.findall(pattern,  string[,  flags])

        findall(string[,  pos[,  endpos]])

        作用:在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回

        例:查找[]包括的内容(贪婪和非贪婪查找)
>>>  r1  =  re.compile('([.*])')

>>>  print  (re.findall(r1,"hello[hi]heldfsdsf[iwonder]lo"))

[]

>>>  print  (re.findall(r1,"hello.[hi]heldfsdsf[iwonder]lo"))

['.']

>>>  r1  =  re.compile('([.*?])')

>>>  print  (re.findall(r1,"hello[hi]heldfsdsf[iwonder]lo"))

[]

>>>  print  (re.findall(r1,"hello.[hi]heldfsdsf[iwonder]lo"))

['.']

>>>  r1  =  re.compile('([s*])')

>>>  print  (re.findall(r1,"hello[hi]heldfsdsf[iwonder]lo"))

['s',  's']

>>>  r1  =  re.compile('([s*?])')

>>>  print  (re.findall(r1,"hello[hi]heldfsdsf[iwonder]lo"))

['s',  's']

>>>  print  (re.findall('[0-9]{2}',"fdskfj1323jfkdj"))

['13',  '23']

>>>  print  (re.findall('[0-9]{3}',"fdskfj1323jfkdj"))

['132']

>>>  print  (re.findall('([0-9][a-z])',"fdskfj1323jfkdj"))

['3j']

>>>  print  (re.findall('(?=www)',"afdsfwwwfkdjfsdfsdwww"))

['',  '']

>>>  print  (re.findall('(?<=www)',"afdsfwwwfkdjfsdfsdwww"))

['',  '']
finditer

        re.finditer(pattern,  string[,  flags])

        finditer(string[,  pos[,  endpos]])

        说明:和  findall  类似,在字符串中找到正则表达式所匹配的所有子串,并组成一个迭代器返回。

sub

        re.sub(pattern,  repl,  string[,  count,  flags])

        sub(repl,  string[,  count=0])

        说明:在字符串  string  中找到匹配正则表达式  pattern  的所有子串,用另一个字符串  repl  进行替换。如果没有找到匹配  pattern  的串,则返回未被修改的  string。repl  既可以是字符串也可以是一个函数。

        例:
>>>  p  =  re.compile('(one|two|three)')

>>>  print  (p.sub('num','one  word  two  words  three  words  apple',  2))

num  word  num  words  three  words  apple

>>>  print  (p.sub('num','one  word  two  words  three  words  apple',  1))

num  word  two  words  three  words  apple

>>>  print  (p.sub('num','one  word  two  words  three  words  apple',  3))

num  word  num  words  num  words  apple
subn

        re.subn(pattern,  repl,  string[,  count,  flags])

        subn(repl,  string[,  count=0])

        说明:该函数的功能和  sub()  相同,但它还返回新的字符串以及替换的次数。
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 标准