基于python的-正则表达式

# -*- coding:utf-8 -*-

# re模块是python中内置的用啦支持正则表达式的模块

import re

string = 'hello world'

# 1.准备正则
pattern = re.compile('ello')
# 2.使用正则表达式,从大字符串中搜索小字符串
# match(正则表达式, 要进行查找的大字符串)
# match() 如果找到结果,返回结果对象,没找到返回None
# match() 要查找的子串必须位于大字符串中开头位置才可以匹配成功,如果不在匹配失败,返回None
res = re.match(pattern, string)
if res:
    # group() 用来获取分组信息,分组信息在complie()正则表达式中设置
    print(res.group())
else:
    print('没有匹配到数据')

# search(正则表达式, 要进行查找的大字符串)
# search() 如果找到结果,返回结果对象,没找到返回None
# search() 要查找的子串可以位于大字符串中的任意位置,如果不在匹配失败,返回None
res = re.search(pattern, string)
if res:
    print(res.group())
else:
    print('没有匹配到数据')
# -------------------------------------------------
string2 = 'abcccbccdef'
# .匹配任意字符  *匹配前一个字符0次或无限次
# 默认.*是贪婪模式 尽可能多的匹配数据
pattern = re.compile('a.*b')
res = re.search(pattern, string2)
if res:
    print(res.group())
else:
    print('没有匹配到数据')

# -------------------------------------------------
# 一般使用的都是非贪婪模式,尽可能少的取做数据的匹配
# .*? 非贪婪模式
pattern = re.compile('a.*?b')
res = re.search(pattern, string2)
if res:
    print(res.group())
else:
    print('没有匹配到数据')
# -------------------------------------------------

# +表示匹配前一个字符1次或无限次   .+?非贪婪模式
pattern = re.compile('a.+?b')
res = re.search(pattern, string2)
if res:
    print(res.group())
else:
    print('没有匹配到数据')
# -------------------------------------------------

# | 表示或者,两边的正则符合一个即可
pattern = re.compile('a.*?b|c.*?b')
res = re.search(pattern, string2)
if res:
    print(res.group())
else:
    print('没有匹配到数据')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值