简体   繁体   中英

Python regex search/findall. For a config format

I have a config file in the following format

[COMPONENT1]
KEY1=Value
KEY2=Value
KEY3=Value

[COMPONENT2]
KEY1=Value
KEY2=Value
KEY3=Value
KEY4=Value

I am having trouble writing single line regex for re.findall() , where i can get list/tuple of "COMPONENT"(s) and its respective "KEY(n)" - "VALUE" pairs to iterate through.

so far i have tried the following regex

with open(conf,"r") as config:    
    match = re.findall(r,"?:\[(\w+)\](?:\s*\n*)(?:(\w+(?:\s*=\s*).+)))", config.read())

It's returning

Match 1
Group1: 'COMPONENT1'
Group2: 'KEY1=VALUE'

Match 2
Group1: 'COMPONENT2'
Group2: 'KEY1=VALUE'

I am unable to formulate a regex that can show other 'Key=Value' pair.

Any help on this is really appreciated.

Note: This config format cannot be changed.

This is not something I would suggest using regular expressions for. Regular expressions can be great, but when trying to work with something like a configuration file, they aren't very helpful in structuring what you want to read. Unless you can guarantee that every single relevant line will be structured similarly to [Section Name] or key=value , and only take up one line, and yadda yadda yadda, a regular expression will only complicate the parsing and use of a config file.

In the regular expression you shared, you will only match if and only if a [Section Name] is followed by a key=value pair. key=value pairs on their own lines are being ignored because they are not preceded by a [Section Name] . This is part of what makes using regular expressions a bit inappropriate for things like reading configurations; there are conditionals that arise when structuring your config file that must be dealt with in your regular expression, making it longer and more complicated than it needs to be for the task, or should be when someone needs to maintain it.

ConfigParser is a python module that allows you to easily read .ini-style config files, and I would suggest trying to use it as most of the hard work in reading arbitrary key=value pairs is already solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM