BH15-正则表达式

#coding=utf-8
'''
Created on 2018年3月20日


@author: BH Wong
'''
'''
概念性知识:
    正则表达式本身就是一门编程语言,python通过re模块内嵌进python中。基础部分和
流程:
涉及模块:re模块,函数梳理如下:
    (1) compile() 编译匹配模式,效率更高
    (2) match() 决定RE是否在字符串刚开始的位置匹配。
    (3) search  re.search函数会在字符串内查找模式匹配,只要找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
    (4) findall() re.findall遍历匹配,可以获取字符串中所有匹配的字符串,返回一个列表。
    (5) finditer() 搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。找到 RE 匹配的所有子串,并把它们作为一个迭代器返回。
    (6) split() 按照能够匹配的子串将string分割后返回列表。
    (7) sub() 使用re替换string中每一个匹配的子串后返回替换后的字符串。
    (8) subn() subn(pattern, repl, string, count=0, flags=0)
    
    这里尤其注意 match() search() 和findall()的区别
'''
import re
if __name__ == '__main__':
    '''
            明天我会在这里补上所有的函数示例
            参考地址:https://www.cnblogs.com/tina-python/p/5508402.html
    '''
    #(1)compile 提升效率
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    bh = re.compile('\w+oo\w+')
    print(bh.findall(text))
    #(2) match 匹配行首 ,search 匹配字符串中第一个出现的pattern并使用group()返回
    #print(re.match('cool',text).group())
    print(re.search('cool',text).group())
    #(3)findall 返回一个list
    print(re.findall('is', text))
    #(4) finditer() 暂时不知道干啥的
    iter = re.finditer('is', text)
    for i in iter:
        print(i.group())
    #(5)split 分割 正则的分割
    print(re.split(',', text))
    #(6) sub 替换,subn替换 返回替换后的字符串和替换的次数。
    print(re.sub(',','-', text))
    print(re.subn(',','-', text))
    #习题1 获取 info 中的"http://www.baidu.com" 和 baidu
    info = '<a href="http://www.baidu.com">baidu</a>'
    d = re.split('>', info)
    internet = re.split('=', d[0])
    div = re.split('<', d[1])
    print(internet[1],div[0])
    #习题2
    str = "one1two2three3four4"
    d = re.split('[a-z]+', str)
    print(d)
    #习题3
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    d = re.findall(r'\w*oo\w*', text)
    print(d)
    print(re.search('com','Comwww.runcomoob').group())
    
    #习题4
    '''  
            要求完成下面2个小功能:
    1.1 关闭[img]标签
    1.2 将url()中的["]转为[']
    '''
    info = 'test,&nbsp;url("http://www.baidu.com")&,dddddd "="" <svg></svg><path></path><img src="http://www.baidu.com">ininnnin<img src="http://www.dd.com">'
    d = re.findall('<img\s\w+=\"\w+:\//\w+\.\w+\.\w+">', info)
    for i in d:
        info = re.sub(i, i+'</img>', info)
    print(info)
    print(re.sub('"', '\'', info, 2))
    
    
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值