gpt4 book ai didi

Python 或正则表达式和非空结果

转载 作者:行者123 更新时间:2023-11-28 22:42:40 24 4
gpt4 key购买 nike

我需要找到一个可以采用两种不同形式的子字符串:

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

我怎样才能让 Python 不返回空字符串,并且只在可以进行匹配的地方给我结果?

最佳答案

findall 返回捕获的组,在 documentation 中说明:

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.

你想在一个捕获组中使用交替,我会这样写:

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

关于Python 或正则表达式和非空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31499060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com