簡體   English   中英

如何使用 python 和正則表達式在文件的一部分中找到多個匹配組?

[英]How can I find multiple match groups in a section of a file with python and regex?

我正在嘗試使用 python 和正則表達式來解析 php 配置文件並確定啟用(1)或禁用(0)的插件。 在 php 文件中有一個插件部分,我只想從該部分返回數據。 問題是我不知道如何只查看文件中的插件部分。 我目前正在使用 python 的 findall 來嘗試解決這個問題。

<?php
return [
    'plugins' => [
        'Store' => 1,
        'Directory' => 1,
        'Theme' => 0
    ],
    'stores' => [
        'internal' => [
            '1' => [
                'id' => 0,
                'sort_order' => 0,
                'group_id' => 0
            ]
        ]
    ],
    'themes' => [
        'default' => [
            'id' => 1,
            'path' => 'var/www/html/themes'
        ]
    ]
];

這是我用來嘗試解析數據的代碼

f = open("config.php","r")
contents = f.read()
f.close()

data = re.findall(r"'(\w+)'.+?(1|0)[,\n]+?",contents)
print(data)

當我運行 python 代碼時,我得到了

[('Store', '1'), ('Directory', '1'), ('Theme', '0'), ('id', '0'), ('sort_order', '0'), ('group_id', '0'), ('id', '1')]

如何使用我的 python/regex 代碼得到這個結果?

[('Store', '1'), ('Directory', '1'), ('Theme', '0')]

(僅來自文件這一部分的數據)

    'plugins' => [
        'Store' => 1,
        'Directory' => 1,
        'Theme' => 0
    ],

很可能有更好的方法,但這很好用。

首先用正則表達式隔離plugins部分:

isolated = re.search(r"'plugins' => \[((\n|.)*?)\]", contents).group(1)

接下來運行您已經編寫的正則表達式:

data = re.findall(r"'(\w+)'.+?(1|0)[,\n]+?", isolated)
print(data)
# [('Store', '1'), ('Directory', '1'), ('Theme', '0')]

暫無
暫無

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

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