Python 正则学习(一)

1. Match() 和 Search() 的区别:

    match试图从字符串起始部分匹配,search不但会搜索字符中字符串中的第一次出现的位置,而且严格的从左往右搜索

m = re.match('foo', 'seafood')  #匹配失败
if m is not None:
    print(m.group())
m = re.search('foo', 'seafood')
if m is not None:
    print(m.group())    #foo

2. 创建字符集([ ])

bt = '[cr][23][dp][o2]'
m = re.match(bt, 'c3po')
if m is not None:
    print(m.group()) ##c3po

3. 匹配多个字符串 (|)

bt = 'bat|bet|bit'
m = re.match(bt, 'bat')
if m is not None:
    print(m.group())  # bat

4. 分组

m = re.match('(\w\w\w)-(\d\d\d)', 'abc-123')
if m is not None:
    print(m.group())  # abc-123
    print(m.group(1))  # abc
    print(m.group(2))  # 123
    print(m.groups())  # ('abc', '123')

5. findall()

m = re.findall('car', 'carry the barcardi to the car')
if m is not None:
    print(m) # ['car', 'car', 'car']

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值