我有一个这样的=>
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']
尝试使用 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'>
尝试使用 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
如果您只需要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