2022-05-05 11:01

# 如何判断正则表达式的finditer结果(迭代器?)是否为空?(OpenJudge 054 电话号码)(语言-python)

###### 就是我用正则表达式匹配后,用的是finditer,然后想要判断是否非空,不管是用if list(tags) != []: 还是if numbers:

``````import re
p_tag = r'(<([a-z]+)>).*?(</\2>)'    #group(1)首标签 (2)标签名 (3)尾标签
p_num = r'\((\d\d?)\)\-\d{3}(?!\d)'     #group(1)区号 (2)预查条件
n = eval(input())
input_list = []
for i in range(n):
input_list.append(input())
for s in input_list:
tags = re.finditer(p_tag,s)
count_line = 0
#if list(tags) != []:     <------不用管缩进,总之加上这条程序就出不了结果但也不报错-------
for tag in tags:
count_tag = 0
line = tag.group(1)
numbers = re.finditer(p_num,tag.group(0))
#if numbers:         <--------------------这条也是一样--------------------
for num in numbers:
line += num.group(1)+','
count_line += 1
count_tag += 1
if count_tag != 0:
print(line[:-1] + tag.group(3))
if count_line == 0:
print("NONE")

``````

``````import re
p_tag = r'(<([a-z]+)>).*?(</\2>)'    #group(1)首标签 (2)标签名 (3)尾标签
p_num = r'\((\d\d?)\)\-\d{3}(?!\d)'     #group(1)区号 (2)预查条件
n = eval(input())
input_list = []
for i in range(n):
input_list.append(input())
for s in input_list:
tags = re.finditer(p_tag,s)
#count_line = 0
if list(tags) != []:     #<------不用管缩进,总之加上这条程序就出不了结果但也不报错-------
print("存在匹配标签")   #<------到这里还是有显示的--------------------------
count_line = 0
for tag in tags:
print("each tag:")    # <--------这条就没有不显示了-------------------------
count_tag = 0
line = tag.group(1)
numbers = re.finditer(p_num,tag.group(0))
if numbers:
print("存在匹配数字")
for num in numbers:
line += num.group(1)+','
count_line += 1
print(line[:-1] + tag.group(3))
if count_line == 0:
print("NONE-所有标签都没有匹配数字")
else:
print("NONE-没有匹配标签")
``````

``````1
<bb>(01)-123<a>bbb(02)-2784KK</a><xy>stk(1)-123(03)-345b</xy>(04)-123</xy><z>(05)-123</zz>zz<yy>(06)-123</yy>

NONE-所有标签都没有匹配数字

``````