Python 正则表达

1.match和search的区别

def re_method():
# search vs. Match
s = 'abcd'
print(re.search(r'c', s))
print(re.match(r'c', s))
if __name__ == '__main__':
re_method()

返回值为
<_sre.SRE_Match object; span=(2, 3), match='c'>
None

match从字符串的第一个开始进行匹配,可以通过在前面加.*的方式找到,其中.表示匹配任意字符
re.match(r'.*c', s)
search:搜索字符串任意位置的匹配,可以通过添加^^表示某一字符串的开始位置
re.search(r'^c', s)

2.split

分割字符,按照非字母字符
re.split(r'\W+','I love you')

[‘I’, ‘love’, ‘you’]

\W:表示非字母字符,\w:表示字母字符,如果按照\w分割,那么会是另一种结果

3.findall和finditer

findall根据正则表达式从左到右搜索匹配项,返回匹配的字符串列表(跟search是对应的关系,search是只要搜索到匹配的第一个,它就会停下来,findall是会继续往下查找)
re.findall(r'\w+','I love you')
输出['I', 'love', 'you']

re.findall(r'\d+\.?\d*', 'The beef is $5.6,I like to take 2 piece',)
输出[5.6 2]

finditer根据正则表达式从左到右搜索匹配项,返回一个迭代器迭代返回MatchObjec

def re_demo():
    s = 'The first price is $9.90 and the second price is $100'

    i = re.finditer(r'\d+\.?\d*', s)
    for m in i:
        print(m.group())
re_demo()

4.sub和subn

字符串替换字符串替换

s = 'The first price is $9.90 and the second price is $100'
    print(re.sub(r"\$\d+\.?\d*",'<number>',s))

subn和sub一样:返回值多了替换的字符串个数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值