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'] >>>
相关推荐
RuoShangM 2020-02-27
Buerzhu 2019-12-02
dailinqing 2019-10-28
chenwen0000 2019-09-07
shijinling0 2019-06-29
LHpython 2019-04-23
Python探路者 2019-04-18
JamesHammer 2019-04-17
PythonBiglove 2018-12-25
JamesHammer 2019-04-05
pythonpycharm 2013-12-25
yoyoshadow 2013-11-20