zoukankan      html  css  js  c++  java
  • 正则表达式-----re库

    1.正则表达式的概念

    a.为什么要用正则?

    用字符串匹配也是可以的:

    startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

    endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。这两种方法注意文件的的匹配最后加

    startswith()方法语法:

    str.startswith(substr, beg=0,end=len(string))

    例子:

    str = "this is string example....wow!!!"
    print (str.startswith( 'this' ))   # 字符串是否以 this 开头
    print (str.startswith( 'string', 8 ))  # 从第八个字符开始的字符串是否以 string 开头
    print (str.startswith( 'this', 2, 4 )) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头

    endswith()方法语法:

    endswith()方法语法:

    例子:

    str = "this is string example....wow!!!";
     
    suffix = "wow!!!";
    print str.endswith(suffix);
    print str.endswith(suffix,20);
     
    suffix = "is";
    print str.endswith(suffix, 2, 4);
    print str.endswith(suffix, 2, 6);

    结果:

    True
    True
    True
    False

    a——应为字符串的匹配每一次都是一个单独的函数来的,简化使用正则

    正则表达式的概念:使用描述字符串来描述匹配一系列符号某个语法规则的字符串;是对字符串操作的一种逻辑公式;处理文本和数据;

    正则表达式的处理过程:一次拿出表达式和文本中的字符比较,如果每一个字符都能匹配,则匹配成功,否则匹配失败

    2.re模块相关方法使用一点点:

    import re
    str1 = '我的工号是00008218ass555'
    #re.search在一个字符串中查找匹配正则表达式的第一个字符串
    gonghao = re.search(r'd+',str1)
    print(gonghao.group())
    str2 = 'adass=123,sdasddd=234,dsadsdf=567'
    #re.findall 在一个字符串中匹配所有的匹配正则的数据
    quanbu = re.findall(r'd+',str2)
    print(quanbu)
    #re.sub 在一个字符串中匹配正则替换字符串
    str3 = '我的测试数字是777'
    def jiayi(chuancan):
        val = chuancan.group()
        jia = int(val)+1
        return str(jia)
    qq=re.sub(r'd+',jiayi,str3)
    print(qq)
    qqq = '666'
    qqqq=re.sub(r'd+',qqq,str3)
    print(qqqq)
    #re.split
    str4 = 'wo: + ni++ = ta  =  qqqqqqqq'
    wq = re.split(r':|=',str4)   #| 这个符号是或者的意思。这个是根据: 或者=来进行分割
    print(wq)

    结果:

    00008218
    ['123', '234', '567']
    我的测试数字是778
    我的测试数字是666
    ['wo', ' + ni++ ', ' ta  ', '  qqqqqqqq']

    查看更详细: http://www.runoob.com/python/python-reg-expressions.html

  • 相关阅读:
    GraphX学习笔记——Programming Guide
    GraphX学习笔记——可视化
    Gephi学习笔记
    Ubuntu16.04安装apache-airflow
    Centos7.0下MySQL的安装
    同时安装anaconda2和anaconda3
    Hive学习笔记——安装和内部表CRUD
    Python爬虫学习——布隆过滤器
    Ubuntu下安装和使用zookeeper和kafka
    Ubuntu16.04安装xgboost
  • 原文地址:https://www.cnblogs.com/Mr-Simple001/p/10550942.html
Copyright © 2011-2022 走看看