zoukankan      html  css  js  c++  java
  • re模块之分组和方法

    import re
    
    # 元字符之| -----> 或的作用,管道符左边为一整体,右边为一整体
    print(re.findall('ka|b', 'abckacckb|k'))
    
    # 元字符之分组()
    print(re.findall('(ad)+', 'adad')) # 这里匹配到了adad,但只显示括号里中的ad
    print(re.findall('(?:ad)+', 'adad')) # 加个?:就可以显示全部匹配了
    res = re.search('(?P<name>D+)(?P<age>d+)', 'alex20alice22') # 这是有名分组;search()只要找到一个满足的就不再找了
    print(res) # 返回结果<re.Match object; span=(0, 6), match='alex20'>;如果匹配不成功,返回则为空
    print(res.group()) # group()方法在search()有用,在findall()没用
    print(res.group('name'))
    print(res.group('age'))
    
    
    '''re模块下的常用方法'''
    
    # findall()返回所有满足匹配条件的结果,放在列表里
    print(re.findall('a', 'alex alice'))
    
    # search()函数会在字符串内查找模式匹配,直到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None
    print(re.search('a', 'alex alice').group())
    
    # match()同search(),不过仅在字符串开始处进行匹配
    print(re.match('a', 'alex alice').group())
    
    # split()字符串分割
    print(re.split(' ', 'hello world man'))
    print(re.split('[ |]', 'hello world |man'))
    print(re.split('[ab]', 'asdbacd'))
    
    # sub()替换,subn()替换并计算替换的次数且返回一个元组
    print(re.sub('d+', 'A', 'hello12hei34hei544'))
    print(re.sub('d', 'A', 'hello12hei34hei544'))
    print(re.sub('d', 'A', 'hello12hei34hei56', 3)) # 最后一个参数代表替换几次
    print(re.subn('d', 'A', 'hello12hei34hei544'))
    
    # compile()编译;可以使用多次,如果需要多次此规则进行匹配可提高效率
    obj = re.compile('d+') # 编写匹配规则并赋值给一个变量
    print(obj.findall('ab1cd22ef333')) # 可以直接调用变量,且方法不再需要编写匹配规则
    
    # finditer()返回的是一个迭代器对象,功能和findall()一样
    msg = re.finditer('d+', 'alex20lhf22yuanhao24')
    print(msg) # 返回的是迭代器对象<callable_iterator object at 0x00000175D1298430>
    print(next(msg)) # <re.Match object; span=(4, 6), match='20'>,和search()方法返回的结果一样,所以可以调用group()方法取值
    print(next(msg).group()) # 上一个next已经取了一个值,只是没有调用group()方法,所以这次取的值是22
    print(next(msg).group()) # 24
    
    # 注意
    print(re.findall('www.(baidu|163).com', 'www.baidu.com')) # ['baidu']这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可
    print(re.findall('www.(?:baidu|163).com', 'www.163.com')) # ['www.163.com']分组里加?:
    while True: print('studying...')
  • 相关阅读:
    概率期望,数学,贪心策略——2020-camp-day1-A
    k染色——2020-camp-day3-C
    树形dp——2020-camp-day3-G
    欧拉回路/路径——2020-camp-day2-H
    dsu on tree——2020-camp-day2-E
    Nim博弈,异或性质——2020-camp-day2-C
    一些视频资料
    开发人员收藏的网站
    各行公认的好书
    资料库链接
  • 原文地址:https://www.cnblogs.com/xuewei95/p/14589664.html
Copyright © 2011-2022 走看看