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')]

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

  • 相关阅读:
    IE8下网页中的视频会遮挡住顶层DIV的解决办法
    Synchronized 偏向锁、轻量级锁、自旋锁、锁消除
    Lock的使用
    Synchronized与ReentrantLock区别总结(简单粗暴,一目了然)
    Java线程池 面试题(精简)
    Java 线程池的认识和使用
    bat等大公司常考java多线程面试题
    Java面试题必备知识之ThreadLocal
    阿里面试题
    Spring中Bean的生命周期
  • 原文地址:https://www.cnblogs.com/yy-is-ing/p/3941516.html
Copyright © 2011-2022 走看看