zoukankan      html  css  js  c++  java
  • Python正则表达式返回首次匹配到的字符及查询的健壮性

    re.findall(pattern,string)会搜索所有匹配的字符,返回的是一个列表,获取首个匹配需要re.findall(pattern,string)[0]访问, 但是如果findall没匹配成功则返回空列表,这时用列表下标去访问元素时就会报IndexError: list index out of range。

    如:

    >>>re.findall('abc','abd')
    []
    >>>re.findall('abc','abd')[0]
    Traceback (most recent call last):
    File "<input>", line 1, in <module>
    IndexError: list index out of range

    我们可以在pattern后面加一个"|$"来生成一个默认的''元素:

    >>>re.findall('abc|$','abd')[0]
    ''
    >>>re.findall('abc|$','abcdef') #注意,无论匹配到与否,都会附加上一个''元素
    ['abc', '']

    同样适用于re.search

    >>> re.search('d+|$', 'aa33bbb44').group()
    '33'
    >>> re.search('d+|$', 'aazzzbbb').group()
    ''

    如果不加|$的话:

    >>>re.search('d+', 'aazzzbbb').group() #search没匹配上,再用.group()就会报错
    Traceback (most recent call last):
    File "<input>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'group'

    参考:https://stackoverflow.com/questions/38579725/return-string-with-first-match-regex

  • 相关阅读:
    几个简单的定律
    poj 2443 Set Operation 位运算
    博弈论 wythff 博弈
    BZOJ 2120 树状数组套平衡树
    HDU 1392 凸包
    ZOJ 1648 线段相交
    HDU 1756 点在多边形内
    SPOJ 1811 LCS 后缀自动机
    BZOJ 1901 树状数组+函数式线段树
    HDU 1086 线段相交(不规范相交模板)
  • 原文地址:https://www.cnblogs.com/huahuayu/p/8253882.html
Copyright © 2011-2022 走看看