简体   繁体   English

Python或正则表达式中,非空结果

[英]Python or in regex and non empty result

I need to find a substring that can take 2 different forms: 我需要找到一个可以采用2种不同形式的子字符串:

>>> test = '348249432'
>>> x = re.findall("([2][0][0-9]{7})|([3][0-9]{8})", test)
>>> x
[('', '348249432')]

How can I ask Python not to return empty string, and to only give me result where a matching could have been done ? 我怎样才能要求Python不要返回空字符串,而只给我可以进行匹配的结果?

findall returns the captured groups, stated in the documentation : findall返回捕获的组,如文档所述

If one or more groups are present in the pattern, return a list of groups; 如果该模式中存在一个或多个组,则返回一个组列表;否则,返回一个列表。 this will be a list of tuples if the pattern has more than one group. 如果模式包含多个组,则这将是一个元组列表。 Empty matches are included in the result unless they touch the beginning of another match . 空匹配项将包括在结果中,除非它们碰到另一个匹配项的开头

You want to use alternation inside of one capturing group, and I would write this as: 您想在一个捕获组中使用交替,我将其写为:

>>> test = '348249432'
>>> re.findall("(20[0-9]{7}|3[0-9]{8})", test)
['348249432']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM