查找多个特定长度的子字符串(查找字符串中的5位和6位数字)

问题描述 投票:0回答:2

我有一个这样的=>
list_o_text= [ '随机字符串 1 2 3 45 6789 999999 22222', '技术报告示例 444444' ]

list_o_text 中的每个字符串肯定包含一个或多个 5 或 6 位数字。

我最近发现了 RE 模块。然而我在寻找合适的函数来搜索它们时遇到了问题。

尝试使用 findall()

import re

list_o_text= [ 'Random string 1 2 3 45 6789 999999 22222', 'Example tech report 444444' ]

for n in range(len(list_o_text)):
find = re.findall('\d{5}+',list_o_text[n])
print(find)

输出:

['99999','22222'] ['44444']

注:六位数‘999999’未完整找到

尝试使用 search()

import re

list_o_text= [ 'Random string 1 2 3 45 6789 999999 22222', 'Example tech report 444444' ]

for n in range(len(list_o_text)):
find = re.search('\d{5}+',list_o_text[n])
print(find

输出:

<re.Match object; span=(28, 33), match='99999'>
<re.Match object; span=(20, 25), match='44444'>

注意:给出位置,并且范围不包含 6 位数字

尝试使用 search().group()

import re

list_o_text= [ 'Random string 1 2 3 45 6789 999999 22222', 'Example tech report 444444' ]

for n in range(len(list_o_text)):
find = re.search('\d{5}+',list_o_text[n]).group()
print(find)

输出:

99999 44444

注:六位数‘999999’未完整找到


复杂的解决方案

我使用了所有三种方法,但无法动摇它还可以更简单的感觉。

输入:

import re

list_o_text= [ 'Random string 1 2 3 45 6789 999999 22222', 'Example tech report 444444' ]

for n in range(len(list_o_text)):
    find_all = re.findall('\d{5}+',list_o_text[n])  
    #1st loop result is ['99999','22222']

    for five_d_num in find_all:
        
        find_start = re.search(five_d_num,list_o_text[n]).start()

        find = re.search('\d+',list_o_text[n][find_start: ]).group()
    
        print(find)

输出:

999999 22222 444444

python regex
2个回答
1
投票

图案

\d{5}+
不是你需要的,你想要的
\d{5,6}

我强烈推荐regex101.com来构建和测试正则表达式模式。该网站提供了该模式组件的详细分类。


0
投票

如果您只需要5位和6位数字,则可以使用

[0-9]{5,6}
。但是,如果您想要 5 位或更多数字,您可以使用
[0-9]{5,}

您可以在 char 类

{}
或组(例如
{min_count, max_count}
[]
)之后以
(?:)
的格式使用
()

import re

list_o_text = ['Random string 1 2 3 45 6789 999999 22222',
               'Example tech report 444444', 'Example tech report 7777777 8888888888888']

output_a = re.findall(r'[0-9]{5,}', ' '.join(list_o_text))

output_b = ' '.join(output_a)

print(output_a)
print(output_b)

代码中有两个输出,您可以选择任意一个。

打印:

['999999', '22222', '444444', '7777777', '8888888888888'] 999999 22222 444444 7777777 8888888888888

© www.soinside.com 2019 - 2024. All rights reserved.