python - Python正则表达式多次重复相同的匹配
问题描述
设想:
我正在使用打开一个 XML 文件作为文本open('name of file', 'r')
我正在寻找一个特定的模式。
尽管 xml 文档中只有 1 行具有我正在寻找的模式,但我得到它多次返回。
我知道它只出现一次,因为我自己创建了文件。我只拿起1个文件。
我究竟做错了什么?
这是我的代码:
src_q_regex = re.compile('\[sales\]\.\[customer\]', re.IGNORECASE)
for a in range(0, len(ssis_txt_files_2)):
open_sample_file = open(ssis_txt_files_2[a], 'r')
whatever = open_sample_file.readlines()
whatever = ''.join(whatever)
#for x in range(0,len(whatever), 1):
for x in range(0,10, 1):
source_found = src_q_regex.search(whatever)
if source_found:
thing = str(source_found.group())
print(str(thing))
这是输出:
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
[Sales].[Customer]
我希望它返回:
`[Sales].[Customer]` <---just 1 time because that is the only number of times it appears.
编辑#1:
我删除了“hi”这个词,因为我只是用它来测试并用实际变量替换它。
解决方案
您正在循环 10 次for x in range(0,10, 1):
所以单个匹配被打印 10 次。
推荐阅读
- r - 2 个多重响应集之间的频率
- python - 无法将 json.dumps 与 with python 语句一起使用
- android - 如何将android视频播放器从活动过渡到片段?
- python - 如何将 numpy 1D 数组插入 numpy 3D 数组?
- php - 为 php 存储的 .env 文件在哪里
- angular - 如何在 Angular 6 中过滤 FormArray 元素
- c# - 按不同类型的列表属性对列表进行排序
- python - 如何使用 Graphene GraphQL 解析嵌套在另一种类型中的字段?
- python - python3,如何下载zip文件
- java - 使用 FlyingSaucer (Itext5) 使图像居中的问题:“margin:auto and display block”并从 XHTML 解析为 PDF