zoukankan      html  css  js  c++  java
  • Python瓦匠 —— 正则表达式(五)

    一 通配字符

    .(句点)字符被称为通配符,它匹配除了换行符以外的所有字符。

    例如:

    >>> atRegex = re.compile(r'.at')
    >>> atRegex.search('The cat in the hat sat on the flat mat.')
    <_sre.SRE_Match object; span=(4, 7), match='cat'>

    二 用点-星号匹配所有的字符

    (.*)表示匹配任意文本。

    >>> import re
    >>> nameRegex = re.compile(r'firstname:(.*)')
    >>> nameRegex.search('firstname:liu').group()
    'firstname:liu'

    (.*)使用‘贪心’模式:它总是匹配尽可能多的文本。

    (.*?)表示非贪心模式匹配所有文本。

    例如:

    >>> xRegex = re.compile(r'<.*?>') #匹配所有<>的文本,非贪心模式
    >>> mo = xRegex.search('<To serve man> for dinner.')
    >>> mo.group()
    '<To serve man>'
    >>> 

    贪心模式:

    >>> xRegex = re.compile(r'<.*>') #贪心模式
    >>> mo = xRegex.search('<To serve man> for dinner.>')
    >>> mo.group()
    '<To serve man> for dinner.>' #匹配最大的文本

    三 用句点字符匹配换行

    点-星匹配除换行之外所有字符。通过传入re.DOTALL作为re.compile()的第二个参数,可以让句点字符匹配所有字符,包括换行。

    例如:

    #匹配所有文本,不包括换行符
    >>> name = re.compile(r'.*')
    >>> no = name.search('firstname = liu
    Lstname = liuyong')
    >>> no.group()
    'firstname = liu'
    
    #匹配所有文本,包括换行符
    >>> name = re.compile(r'.*',re.DOTALL)
    >>> no = name.search('firstname = liu
    Lstname = liuyong')
    >>> no.group()
    'firstname = liu
    Lstname = liuyong'
  • 相关阅读:
    Eclipse
    svn 常用
    spidermonkey编译
    float format 显示
    点击6次修改服务器地址
    UITextField字数限制
    UINavigationController
    运行时runtime
    IOS 技术与面试
    Cocos2dx笔记
  • 原文地址:https://www.cnblogs.com/BeautifulSoup/p/8410592.html
Copyright © 2011-2022 走看看