python 正则语法

来源:互联网 发布:2017淘宝现在还能刷吗 编辑:程序博客网 时间:2024/06/16 07:34

通配符: . 匹配任何字符

import restr1='imooc python'pa=re.compile('.')ma=re.findall(str1)print ma输出:i

对特殊字符进行转义: \

字符集:
[a-z]可以匹配任意小写字母

import restr1='imooc.sjh a ImoocSjh,,,!!'pa=re.compile('[a-z]')ma=re.findall(pa,str1)print ma输出:['i', 'm', 'o', 'o', 'c', 's', 'j', 'h', 'a', 'm', 'o', 'o', 'c', 'j', 'h']

[a-zA-Z0-9]可以匹配任意字母数字

import restr1='imooc.sjh a ImoocSjh,,,!!'pa=re.compile('[a-zA-Z0-9]')ma=re.findall(pa,str1)print ma输出:['i', 'm', 'o', 'o', 'c', 's', 'j', 'h', 'a', 'I', 'm', 'o', 'o', 'c', 'S', 'j', 'h']

反转字符集 [^a]可以匹配除a以外的字符

import restr1='imooc.sjh a ImoocSjh,,,!!'pa=re.compile('[^a]')ma=re.findall(pa,str1)print ma输出:['i', 'm', 'o', 'o', 'c', '.', 's', 'j', 'h', ' ', ' ', 'I', 'm', 'o', 'o', 'c', 'S', 'j', 'h', ',', ',', ',', '!', '!']

选择符:| 管道符号,只匹配指定的字符串

str1='imooc.sjh a ImoocSjh,test,,!!'pa=re.compile('sjh|test')ma=re.findall(pa,str1)输出:['sjh', 'test']

子模式:当不需要对整个模式使用选择符 时,用()括起

str1='imooc.sjh a ImoocSjh,stest,,!!'pa=re.compile('s(jh|test)')ma=re.findall(pa,str1)输出:['jh', 'test']

可选项:在子模式后面加 ? 可以出现在匹配字符串,但不是必须的。
1.

str1='http://www.imooc.com'pa=re.compile('(http://)?(www\.)?(imooc\.com)')ma=re.findall(pa,str1)输出:[('http://', 'www.', 'imooc.com')]

2.

str1='www.imooc.com'pa=re.compile('(http://)?(www\.)?(imooc\.com)')ma=re.findall(pa,str1)输出:[('', 'www.', 'imooc.com')]

3.

str1='http://www.imooc'pa=re.compile('(http://)?(www\.)?(imooc\.com)')ma=re.findall(pa,str1)输出:[]

重复子模式:(pattern)*:模式可以重复0或多次
(pattern)+:模式可以重复1或多次
(pattern){m,n}:模式可以重复m~n次
1.

str1=' www.python.org  .python.org  wwwwwww.python.org w.python.org wwww.python.org'pa=re.compile('w*\.python\.org')ma=re.findall(pa,str1)输出:['www.python.org', '.python.org', 'wwwwwww.python.org', 'w.python.org', 'wwww.python.org']

2.

str1=' www.python.org  .python.org  wwwwwww.python.org w.python.org wwww.python.org'pa=re.compile('w+\.python\.org')ma=re.findall(pa,str1)输出(没有匹配'.python.org'):['www.python.org', 'wwwwwww.python.org', 'w.python.org', 'wwww.python.org']  

3.

str1=' www.python.org  .python.org  wwwwwww.python.org w.python.org wwww.python.org'pa=re.compile('w{3,4}\.python\.org')ma=re.findall(pa,str1)输出:['www.python.org', 'wwww.python.org', 'wwww.python.org']
原创粉丝点击