python-2.7 - 使用正则表达式获取匹配词的索引
问题描述
我需要一个代码来搜索在字符串中重复的部分单词(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) 并将它添加到列表
解决方案
我找到了解决方案,但需要一项增强功能,即在获得索引后,我需要在该索引之前再次搜索单词 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])
推荐阅读
- rendering - 模拟高斯光束通过镜头时,PovRay 渲染停止
- mysql - 如何连接来自同一个表的数据点?
- python-3.x - 从数据框和 Pandas 系列制作字典
- spring-boot - 弹簧靴和招摇/openapi
- c++ - 如何将具有 .c 和 .h 文件的现有项目转换为 Visual Studio 2019 中的动态链接库?
- c# - 检测不受控制的点击
- c - 这个公式在 quad_mpi.c 中是什么意思?
- c++ - 长 cpp 变量的推荐代码样式
- pdf-generation - 通过 chrome headless 生成的 PDF 上的字体问题
- postgresql - 组合连接查询表 1 varchar-column-with-int-column 用于表 2