Python正则

1.re.compile()

2.match()

默认头开始匹配,现在是可以从指定位置开始匹配

>>> import re
>>> r=re.compile("go*d")
>>> r.match("Life can be good")
>>> r.match("Life can be good",13)
>>> r.search("Life can be good")
<_sre.SRE_Match object; span=(12, 16), match='good'>
>>> r=re.compile("b.\sg")
>>> r.search("Life can be good")
<_sre.SRE_Match object; span=(9, 13), match='be g'>
>>> r=re.compile("\w.\sg")
>>> r.search("Life can be good")
<_sre.SRE_Match object; span=(9, 13), match='be g'>
>>> r=re.compile("\\b\w..?\s")
>>> r.findall("Life can be good")
['can ', 'be ']
>>> r=re.compile("b\w*",re.I)
>>> s='''Life can be good;
... Life can be bad;
... Life is mostly cheerful;
... But sometimes sad.'''
>>> r.sub("*",s)
'Life can * good;\n... Life can * *;\n... Life is mostly cheerful;\n... * sometimes sad.'
>>> r.sub("*",s,2)
'Life can * good;\n... Life can * bad;\n... Life is mostly cheerful;\n... But sometimes sad.'
>>> new=r.subn("*",s)
>>> print(new[0])
Life can * good;
... Life can * *;
... Life is mostly cheerful;
... * sometimes sad.
>>> print(new[1])
4
>>>
其中new[1]表示返回匹配的个数

而new[1]表示匹配的字符串

>>> s='''Life can be good;
... Life can be bad;
... Life is mostly cheerful;
... But sometimes sad.'''
>>> r=re.compile("\s")
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    r=re.compile("\s")
NameError: name 're' is not defined
>>> import re
>>> r=re.compile("\s")
>>> news=r.spile(s)
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    news=r.spile(s)
AttributeError: '_sre.SRE_Pattern' object has no attribute 'spile'
>>> neews=r.split(s)
>>> neews
['Life', 'can', 'be', 'good;', '...', 'Life', 'can', 'be', 'bad;', '...', 'Life', 'is', 'mostly', 'cheerful;', '...', 'But', 'sometimes', 'sad.']
>>> news=r.split(s,4)
>>> news
['Life', 'can', 'be', 'good;', '... Life can be bad;\n... Life is mostly cheerful;\n... But sometimes sad.']
>>> r=re.compile("b\w*",re.I)
>>> ne=r.spilt(s)
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    ne=r.spilt(s)
AttributeError: '_sre.SRE_Pattern' object has no attribute 'spilt'
>>> ne=r.split(s)
>>> ne
['Life can ', ' good;\n... Life can ', ' ', ';\n... Life is mostly cheerful;\n... ', ' sometimes sad.']
>>> r=re.comile("\w*e")
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    r=re.comile("\w*e")
AttributeError: 'module' object has no attribute 'comile'
>>> r=re.compile("\w*e",re.I)
>>> news=r.split(s)
>>> news
['', ' can ', ' good;\n... ', ' can ', ' bad;\n... ', ' is mostly ', 'rful;\n... But ', 's sad.']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值