首页 > 解决方案 > 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”这个词,因为我只是用它来测试并用实际变量替换它。

标签: pythonregex

解决方案


您正在循环 10 次for x in range(0,10, 1):

所以单个匹配被打印 10 次。


推荐阅读