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

    Python的正则表达式的模块名字是‘re'

    >>> import re

    >>> rawString = r'This is a normal string.'

    >>> rawString

    'This is a normal string.'

    >>> string = 'This is a normal string.'

    >>> string

    'This is a

    normal string.'

    ==================================

    >>> match = re.match(r'dog', 'dog cat dog')

    >>> match.group(0)

    'dog'

    .match()函数只能从字符串最开始进行匹配

    >>> match = re.match(r'cat', 'dog cat dog')

    >>> match

    >>>

    ===================================

    .search()函数可以在字符串里从左到右自有匹配,不过只能匹配一次,查找到一个匹配项之后就停止

    >>> match = re.search(r'cat', 'dog cat dog')

    >>> match.group(0)

    'cat'

    ====================================

    .findall()函数可以在字符串里,查找到所有匹配项,并放入一个列表中

    >>> match = re.findall(r'dog', 'dog cat dog')

    >>> match

    ['dog', 'dog']

    >>> match = re.findall(r'cat', 'dog cat dog')

    >>> match

    ['cat']

    =====================================

    >>> match = re.search(r'dog', 'dog cat dog')

    >>> match.start()

    0

    >>> match.end()

    3

    .start()与.end()两个函数,可用于告诉该匹配对象在字符串中的开始位置与结束为止

    =====================================

    >>> contaciInfo = 'Doe, John: 555-1212'

    >>> match = re.search(r'(?P<.last>w+), (?P<first>w+): (?P<phone>S+)', contactInfo)

    >>> match.group('last')

    'Doe'

    >>> match.group('first')

    'John'

    >>> match.group('phone')

    '555-1212'

    可以直接给分组命名,方便后续使用。不过.findall()函数不适用于命名

    >>> re.findall(r'(w+), (w+): (S+)', contactInfo)

    [('Doe', 'John', '555-1212')]

    ====================================================

  • 相关阅读:
    为什么要用设计模式?先看看6大原则(一)
    git版本库的创建和yaf框架环境的部署
    laravel日常小问题
    Session store not set on request.
    phpstudy集成环境安装lavarel
    html中提交表单并实现不跳转页面处理返回值
    document load 与document ready的区别
    定时器优化
    放大镜
    子组件调用父组件的方法并传递数据
  • 原文地址:https://www.cnblogs.com/yy-is-ing/p/3941516.html
Copyright © 2011-2022 走看看