return string with first match Regex

前端 未结 6 1846
既然无缘
既然无缘 2020-11-27 18:26

I want to get the first match of a regex.

In this case, I got a list:

text = \'aa33bbb44\'
re.findall(\'\\d+\',text)

6条回答
  •  失恋的感觉
    2020-11-27 18:58

    You could embed the '' default in your regex by adding |$:

    >>> re.findall('\d+|$', 'aa33bbb44')[0]
    '33'
    >>> re.findall('\d+|$', 'aazzzbbb')[0]
    ''
    >>> re.findall('\d+|$', '')[0]
    ''
    

    Also works with re.search pointed out by others:

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

提交回复
热议问题