Reputation: 203
I have a list of multiple items. Need to create a loop that finds an item from the list and prints it out. If item not found prints out only once that it hasn't been found.
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
break
else:
print('wrong format')
Currently it prints out multiple times that it hasn't been found. When it matches the regex it prints out at the end. I only want the If Else to prints "wrong format" once.
currently prints out wrong format wrong format wrong format wrong format wrong format wrong format wrong format "DeviceX Regex matched"
Upvotes: 0
Views: 749
Reputation: 1306
This should solve your problem.
flag = 0
for x in range(len(regs)):
rex = regs[x]
if re.match(rex, hostname):
print(dev[x], 'Regex matched')
flag = 1
break
if flag == 0:
print('wrong format')
Upvotes: 0
Reputation: 473
I think you can make it shorter using comprehensive list such as:
if len([r for r in regs if re.match(r, hostname)]) == 1:
print(dev[regs.index([r for r in regs if re.match(r, hostname)][0])], 'Regex matched')
else:
print('not found')
Upvotes: 0
Reputation: 4630
Use else
with for
.
As you are breaking out of the for loop as soon as you find one item, the below code will work fine:
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
break
else:
# Does not execute only when a break statement
# is executed inside the for loop.
print('wrong format')
Upvotes: 1
Reputation: 1290
You can maintain a flag variable as follows.
matched = False
for x in range(len(regs)):
rex = regs[x]
if re.match(rex, hostname):
print(dev[x], "Regex matched!")
matched = True
break
if not matched:
print("Wrong format")
Upvotes: 0
Reputation: 5415
It is printed multiple times, because there are multiple times where the current value does not match. A simple way to fix this is to use a flag, like so:
value_found = False
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
value_found = True
break
if not value_found:
print('wrong_format')
Upvotes: 0