python正则表达式1

2018-06-18 02:00:53来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

使用正则表达式,需要导入re这个模块

1 >>> import re
2 >>> pattern=r'abc'
3 >>> str='abcdefghijabc11111abc'
4 >>> re.findall( pattern, str )
5 ['abc', 'abc', 'abc']
6 >>> 

r定义正则表达式的规则,这里匹配abc这个字符串

元字符([])匹配一个范围

>>> str="abc afc awc"
>>> pattern=r"a[bfw]c"
>>> re.findall( pattern, str )
['abc', 'afc', 'awc']
>>> pattern=r"a[bf]w"
>>> re.findall( pattern, str )
[]
>>> pattern=r"a[bf]c"
>>> re.findall( pattern, str )
['abc', 'afc']
>>> 

^:以...开头,用在中括号里面表示非(取反,或者说排除)

1 >>> import re
2 >>> str="ghostwu:hi my name is ghostwu, nice to meet you!"
3 >>> pattern=r"ghostwu"
4 >>> re.findall( pattern, str )
5 ['ghostwu', 'ghostwu']
6 >>> pattern=r"^ghostwu"
7 >>> re.findall( pattern, str )
8 ['ghostwu']
9 >>> 
1 >>> str="abc"
2 >>> pattern=r"a[b]c"
3 >>> re.findall( pattern, str )
4 ['abc']
5 >>> pattern=r"a[^b]c"
6 >>> re.findall( pattern, str )
7 []
8 >>> 

$:以....结尾

>>> str="ghostwu:hi my name is ghostwu, nice to meet you! Hanmeimei: Hi,ghostwu"
>>> pattern=r"ghostwu"
>>> re.findall( pattern, str )
['ghostwu', 'ghostwu', 'ghostwu']
>>> pattern=r"ghostwu$"
>>> re.findall( pattern, str )
['ghostwu']
>>> 

$在中括号中被当做普通的字符串匹配

 1 >>> pattern=r"a[bcd$]"
 2 >>> re.findall( pattern, 'ab' )
 3 ['ab']
 4 >>> re.findall( pattern, 'ac' )
 5 ['ac']
 6 >>> re.findall( pattern, 'ad' )
 7 ['ad']
 8 >>> re.findall( pattern, 'abe' )
 9 ['ab']
10 >>> re.findall( pattern, 'a$' )
11 ['a$']
12 >>> 

转义字符 \

 1 >>> str="^ghostwu ^ghostwu ^ghostwu"
 2 >>> pattern=r"^ghostwu"
 3 >>> re.findall( pattern, str )
 4 []
 5 >>> pattern=r"ghostwu"
 6 >>> re.findall( pattern, str )
 7 ['ghostwu', 'ghostwu', 'ghostwu']
 8 >>> pattern=r"\^ghostwu"
 9 >>> re.findall( pattern, str )
10 ['^ghostwu', '^ghostwu', '^ghostwu']
11 >>> 

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python全栈开发-Day6 字符编码

下一篇:文件管理