簡體   English   中英

使用正則表達式解析大文本文件

[英]Parsing large text file using regex

我有一個大型文本文件(60Mb),如下所示:

:VPN ()
:add_adtr_rule (true)
:additional_products ()
:addr_type_indication (IPv4)
:certificates ()
:color (black)
:comments ()
:connectra (false)
:connectra_settings ()
:cp_products_installed (false)
:data_source (not-installed)
:data_source_settings ()
:edges ()
:enforce_gtp_rate_limit (false)
:firewall (not-installed)
:floodgate (not-installed)
:gtp_rate_limit (2048)
:interfaces ()
:ipaddr (10.19.45.18)

對於:add_adtr_rule為true的每個實例,都有成千上萬個':add_adtr_rule(false)'條目,我需要ipaddr的值-因此在這種情況下,我需要10.19.45.18。 如何使用正則表達式提取此信息。

我嘗試了以下代碼,該代碼返回一個空列表:

import re

with open("objects_5_0_C-Mod.txt", "r") as f:
    text = f.read()

ip=re.findall(r':add_adtr_rule [\(]true[\)]\s+.*\s+.*\s+.*\s+.*\s+:ipaddr\s+[\(](.*)[\)]', text)
print(ip) 

以下正則表達式應該做到這一點:

(?s)(?:add_adtr_rule\s\(true\)).*?:ipaddr\s\((.*?)\)

參見正則表達式演示/說明

python演示

import re

s = """:VPN () :add_adtr_rule (true) :additional_products () :addr_type_indication (IPv4) :certificates () :color (black) :comments () :connectra (false) :connectra_settings () :cp_products_installed (false) :data_source (not-installed) :data_source_settings () :edges () :enforce_gtp_rate_limit (false) :firewall (not-installed) :floodgate (not-installed) :gtp_rate_limit (2048) :interfaces () :ipaddr (10.19.45.18)"""
r = r"(?s)(?:add_adtr_rule\s\(true\)).*?:ipaddr\s\((.*?)\)"
ip = re.findall(r, s)
print (ip)

您可能想要添加錨點以加快處理速度。 考慮以下示例,其中已啟用MULTILINEVERBOSE

^:add_adtr_rule\ \(true\)   # start of line, followed by :add_ ...
[\s\S]+?                    # everything else afterwards, lazily          
^:ipaddr\ \((?P<ip>[^)]+)\) # start of line, ip and group "ip" between ()

參見regex101.com上的演示


使用您給定的代碼,可以歸結為:

 import re rx = re.compile(r''' ^:add_adtr_rule\\ \\(true\\) [\\s\\S]+? ^:ipaddr\\ \\((?P<ip>[^)]+)\\) ''', re.MULTILINE | re.VERBOSE) with open("objects_5_0_C-Mod.txt", "r") as f: text = f.read() ips = [match.group('ip') for match in rx.finditer(text)] print(ips) 

暫無
暫無

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

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