• 正则表达式基础补充学习


    1. import re
    2. str = 'Hi \n _12'
    3. print(str)

    一、除换行符之外的任意字符

    1. print(re.findall(".",str))
    2. # 连着两个
    3. print(re.findall("..",str))
    4. # 连着三个
    5. print(re.findall("...",str))
    6. print(re.findall("....",str))

    二、 字母、数字、下划线

    1. print(re.findall("\w", str))
    2. # 连着两个
    3. print(re.findall("\w\w", str))
    4. # 连着三个
    5. print(re.findall("\w\w\w", str))

    三、数字

    print(re.findall("\d", str))
    

    四、空格、换行符

    print(re.findall("\s", str))

    五、非字母、数字、下划线

    print(re.findall("\W", str))

    六、非数字

    print(re.findall("\D", str))

    七、非空格、换行符

    print(re.findall("\S", str))

    例:

    1. str2 = 'Hello World 123'
    2. print(re.findall('e', str2))
    3. print(re.findall('ll', str2))
    4. print(re.findall('l\n', str2))
    5. print(re.findall('[abcd]', str2))
    6. print(re.findall('[12][12]', str2))
    7. print(re.findall('[12]..', str2))
    8. print(re.findall('[a-f]', str2))
    9. print(re.findall('[0-2a-e]', str2))
    10. print(re.findall('[^a-e]', str2))
    1. str3 = '122333 abbccc'
    2. print(re.findall("\d{3}", str3))
    3. print(re.findall("\w{3}", str3))
    4. print(re.findall("1*", str3))
    5. print(re.findall("1*2", str3))
    6. print(re.findall("1*3", str3))
    7. print(re.findall("1+", str3))
    8. print(re.findall("1+2", str3))
    9. print(re.findall("1+3", str3))
    10. print(re.findall("\d*", str3))
    11. print(re.findall("\d+", str3))
    12. print(re.findall("\d+3", str3))
    1. import re
    2. str = 'X1Y22Y333Y4444'
    3. # 贪婪匹配
    4. print(re.findall("X.*Y",str))
    5. # ['X1Y22Y33Y']
    6. # 惰性匹配
    7. print(re.findall("X.*?Y",str))
    8. # ['X1Y']
    9. print(re.findall("\d*Y",str))
    10. # ['1Y22Y333Y']
    11. print(re.findall("\d.*?Y",str))
    12. # ['1Y','22Y','333Y']
    1. str2 = 'Hello World 123'
    2. exp = re.compile('\w+')
    3. print(exp.findall(str2))
    1. str3 = 'My name is Martini!'
    2. exp = re.compile('is (.*)!')
    3. print(exp.findall(str3))
    4. str4 = 'My name is Martini!My name is Sam!My name is Tom!'
    5. # exp = re.compile('is (.*)!')
    6. # exp = re.compile('is (.*?)!')
    7. print(exp.findall(str4))
    8. str5 = '''
    9. My name is Martini,and i am 25 years old!
    10. My name is Sam,and i am 27 years old!
    11. My name is Tom,and i am 23 years old!'
    12. exp = re.compile('is (.*?),.*?am (\d+)')
    13. # print(exp.findall(str5))
    14. for i,j in exp.findall(str5):
    15. print(i,j)
  • 相关阅读:
    2022 蔚来杯 牛客多校 后缀自动机(SAM) 马拉车(Manacher)
    全网首发!消息中间件神仙笔记,涵盖阿里十年技术精髓
    发动机连杆加工工艺及镗孔夹具设计
    【cancel请求】切换页面,对上一个页面正在pending的ajax进行取消操作
    01.AJAX 概念和 axios 使用
    vivo亮相博鳌科创会 自研大模型即将发布
    Java如何实现定时任务?
    低代码平台的核心价值与优势
    网关、微服务、Nginx、OpenResty和Kong
    LazySnapping算法详解
  • 原文地址:https://blog.csdn.net/liyunyang2000/article/details/134064160