python正则表达式1

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

>>> import re
 >>> pattern=r'abc'
 >>> str='abcdefghijabc11111abc'
 >>> re.findall( pattern, str )
 ['abc', 'abc', 'abc']
 >>>

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']
>>>

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

>>> import re
 >>> str="ghostwu:hi my name is ghostwu, nice to meet you!"
 >>> pattern=r"ghostwu"
 >>> re.findall( pattern, str )
 ['ghostwu', 'ghostwu']
 >>> pattern=r"^ghostwu"
 >>> re.findall( pattern, str )
 ['ghostwu']
 >>>
>>> str="abc"
 >>> pattern=r"a[b]c"
 >>> re.findall( pattern, str )
 ['abc']
 >>> pattern=r"a[^b]c"
 >>> re.findall( pattern, str )
 []
 >>>

$:以....结尾

>>> 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']
>>>

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

>>> pattern=r"a[bcd$]"
 >>> re.findall( pattern, 'ab' )
 ['ab']
 >>> re.findall( pattern, 'ac' )
 ['ac']
 >>> re.findall( pattern, 'ad' )
 ['ad']
 >>> re.findall( pattern, 'abe' )
 ['ab']
 >>> re.findall( pattern, 'a$' )
 ['a$']
 >>>

转义字符 \

>>> str="^ghostwu ^ghostwu ^ghostwu"
 >>> pattern=r"^ghostwu"
 >>> re.findall( pattern, str )
 []
 >>> pattern=r"ghostwu"
 >>> re.findall( pattern, str )
 ['ghostwu', 'ghostwu', 'ghostwu']
 >>> pattern=r"\^ghostwu"
 >>> re.findall( pattern, str )
 ['^ghostwu', '^ghostwu', '^ghostwu']
 >>>

相关推荐