簡體   English   中英

使用re.match的Python會以長文本掛起

[英]Python using re.match hangs with long text

我有一個帶有域列表的文本文件,我想使用python正則表達式來匹配域和任何子域。

樣本域文件

admin.happy.com
nothappy.com

我有以下正則表達式:

main_domain = 'happy.com'
mydomains = open('domains.txt','r').read().replace('\n',',')
matchobj = re.match(r'^(.*\.)*%s$' % main_domain,mydomains)

該代碼可以很好地處理短文本,但是當我的域文件有100多個條目時,它會掛起並凍結。

有沒有一種方法可以優化正則表達式以處理文本文件中的內容?

(.*\\.)*最有可能導致可怕的回溯。 如果文件每行包含一個域,則最簡單的解決方法是在每行上執行正則表達式,而不是一次執行整個文件:

main_domain = 'happy.com'
for line in open('domains.txt','r')):
    matchobj = re.match(r'^(.*\.)*%s$' % main_domain, line.strip())
    # do something with matchobj

如果您的文件除包含發布格式的域外不包含任何內容,您甚至可以進一步簡化此過程,並且根本不使用正則表達式:

subdomains = []
for line in open('domains.txt','r')):
    line = line.strip()
    if line.endswith(main_domain):
        subdomains.append(line[:-len(main_domain)])

為了避免災難性的回溯,您可以簡化正則表達式:

import re

with open("domains.txt") as file:
    text = file.read()
main_domain = "happy.com"
subdomains = re.findall(r"^(.+)\.%s$" % re.escape(main_domain), text, re.M)

如果還要匹配主域: (r"^(?:(.+)\\.)?%s$"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM