zoukankan      html  css  js  c++  java
  • Python开发应用-正则表达进行排序搜索

      re模块提供了3个方法对输入的字符串进行确切的查询,match和search最多只会返回一个匹配条件的子串,可以理解为非贪婪模式,而findall会返回N个匹配条件的子串,可以理解为贪婪模式

    re.match()

    re.search()

    re.findall()

     #match()方法的工作方式是只有当被搜索字符串的开头匹配模式的时候它才能查找到匹配对象,match返回的是对象,对象里面包含了很多信息

        

    match=re.match(r'dog','dog cat dog') #只要匹配到满足条件的就不匹配了
    print match.group(0)  #dog
    print match.start()    #0
    print match.end()     #3
    match=re.match(r'cat','dog cat dog') 
    print type(match) #<type 'NoneType'>  #因为cat没有在字符串的开头,所以没有匹配到
    

      #search()方法和match()类似,不过search()方法不会限制我们只从字符串的开头查找匹配,它匹配子串,直到匹配到为止或者字符串结束为止

    match=re.search(r'cat','dog cat dog')
    print match.group(0)   #cat,如果不分组,默认就是第0组
    print match.start()    #4
    print match.end()     #7
    

      #findall返回的是列表

      

    match=re.findall(r'dog', 'dog cat dog') #匹配是整个字符串,每个子串都要匹配,匹配到的字符串剔除,后面的字符串要继续匹配正则条件,直到字符串的结尾,有多少匹配多少
    print match #['dog', 'dog']
    

      #使用 mathch.group 分组使用(),分组和不分组匹配的"大子串"都是一样,但是分组之后,可以对这些子组做单独处理。

       

    contactInfo = 'Doe, John: 555-1212'
    match=re.search(r'w+, w+: S+', contactInfo)
    print match.group(0)    #Doe, John: 555-1212
    match = re.search(r'(w+), (w+): (S+)', contactInfo)
    print match.group(0)   #Doe, John: 555-1212,第0组表示匹配的"大子串",满足全部条件
    print match.group(1)    #Doe
    print match.group(2)     #John
    print match.group(3)     #555-1212
    

      #当一个正则表达式有很多分组的时候,通过组的出现次序来定位就会变的不现实。Python还允许你通过下面的语句来指定一个组名:

      

    match = re.search(r'(?P<last>w+), (?P<first>w+): (?P<phone>S+)', contactInfo)
    print match.group('last')  #Doe
    print match.group('first') #John
    print match.group('phone') #555-1212
    

      #尽管findall()方法不返回分组对象,它也可以使用分组。类似的,findall()方法将返回一个元组的集合,其中每个元组中的第N个元素对应了正则表达式中的第N个分组。

       

    match=re.findall(r'w+, w+: S+', contactInfo)
    print match    #['Doe, John: 555-1212']
    

      

    match=re.findall(r'(w+), (w+): (S+)', contactInfo)
    print match   #[('Doe', 'John', '555-1212')]
    

      

  • 相关阅读:
    如何解决selenium打开chrome提示chromedriver.exe已停止工作
    移动端弱网测试 fiddle
    android 真机设备识别不出adb interface
    网络基础知识
    《Mongo权威指南》学习手记
    MongoDB数据库备份
    windows下安装mongoDB(zip版)
    ubuntu apt
    docker 免sudo设置(仅3个命令)
    ubuntu18.04双卡机安装ubidia驱动遇到的坑
  • 原文地址:https://www.cnblogs.com/68xi/p/8547446.html
Copyright © 2011-2022 走看看