Python正则表达式重复相同的匹配多次

时间:2018-08-20 14:41:39

标签: python regex

场景:

我正在使用open('name of file', 'r')

将XML文件作为文本打开。

我正在搜索特定模式。

尽管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”一词,因为我只是为了测试它,而是将其替换为实际变量。

2 个答案:

答案 0 :(得分:2)

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

因此,单场比赛将被打印10次。

答案 1 :(得分:2)

您要循环10次并打印输出10次。

","

只需删除循环:

for x in range(0,10, 1):
    source_found = src_q_regex.search('hi')
    if source_found:
        thing = str(source_found.group())
        print(str(thing))
相关问题