返回第一个匹配正则表达式的字符串 [英] return string with first match Regex

查看:75
本文介绍了返回第一个匹配正则表达式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取正则表达式的第一个匹配项.

在这种情况下,我得到了一个列表:

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

<块引用>

['33', '44']

我可以提取列表的第一个元素:

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

<块引用>

'33'

但这只有在至少有一个匹配时才有效,否则我会得到一个错误:

text = 'aazzzbbb're.findall('\d+',text)[0]

<块引用>

IndexError: 列表索引超出范围

在这种情况下,我可以定义一个函数:

def return_first_match(text):尝试:result = re.findall('\d+',text)[0]除了异常,索引错误:结果 = ''返回结果

有没有办法在不定义新函数的情况下获得该结果?

解决方案

您可以通过添加 |$'' 默认值嵌入到您的正则表达式中:

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

也适用于其他人指出的 re.search:

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

I want to get the first match of a regex.

In this case, I got a list:

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

['33', '44']

I could extract the first element of the list:

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

'33'

But that only works if there is at least one match, otherwise I'll get an error:

text = 'aazzzbbb'
re.findall('\d+',text)[0]

IndexError: list index out of range

In which case I could define a function:

def return_first_match(text):
    try:
        result = re.findall('\d+',text)[0]
    except Exception, IndexError:
        result = ''
    return result

Is there a way of obtaining that result without defining a new function?

解决方案

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

这篇关于返回第一个匹配正则表达式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆