首页 > 解决方案 > 使用正则表达式获取匹配词的索引

问题描述

我需要一个代码来搜索在字符串中重复的部分单词(AIR-*)然后返回其所有索引

我尝试了下面的代码,但我坚持使用哪种方法可以与 re 一起使用来获取所有匹配的单词索引

重新进口

def main(): crt.Screen.Synchronous = True

crt.Screen.Send('show cdp neig '+ '\r')
JGR=crt.Screen.ReadString("#")
strtolist=JGR.split(" ")
king = []
for xxx in strtolist:
    if xxx != "":
        king.append(xxx)
    else:
        continue

crt.Dialog.MessageBox(str(king))
z=[]
q=[]
word = "AIR-.*\w"
listostr = " ".join(king)
search= re.finditer(word,listostr)
crt.Dialog.MessageBox(str(search))
for ind,AP in enumerate(king):
    if AP == word:
        m = ind-5
        z.append(AP[m])
        n = ind-6
        q.append(AP[n])
    else:
        continue
crt.Dialog.MessageBox(str(z))
crt.Dialog.MessageBox(str(q))

#x=re.findall(word,JGR)
#crt.Dialog.MessageBox(str(x))

主要的()

这是我在其中搜索的文本 Name1 Gig 0/20 1 SI WS-C3750X Gig Name2 Fas 2/2 33 TBI AIR-CAP26 Gig 0 Name3 Fas 1/3 14 TBI AIR-CAP15 Gig 0 Name4 Fas 0/1 13 TBI AIR-LAP12 Gig 0 结果是如果我找到 AIR-* 字然后从它的索引我可以去接口索引(Gig 0/20,Fas 2/2.Fas 1/3.Fas 0/1) 并将它添加到列表

标签: python-2.7

解决方案


我找到了解决方案,但需要一项增强功能,即在获得索引后,我需要在该索引之前再次搜索单词 fas,而不是使用固定索引移动 word = "AIR-.*\w"

for ind,AP in enumerate(king):
    if re.search(word, AP):
        m = ind-5
        z.append(m)
        n = ind-6
        q.append(n)
    else:
        continue

for i in z:
    AP1.append(king[i])

for o in q:
    AP2.append(king[o])


for H in range (len(AP1)):
    fin.append(AP2[H] + AP1[H])

推荐阅读