我很难编写正则表达式模式来解析文件中的行。每行都有一个键、一个等号和 0 个或多个值(如果有多个值,则用逗号分隔)。
我正在使用这种模式来分割每一行:
^([A-Z_]*)[ \t]*=[ \t]*\"([A-Z\:0-9\'\-\! ]*)\"(?:,[ \t]*\"([A-Z\:0-9\'\-\! ]*)\")*$
我遇到的问题是它只返回键、第一个和最后一个值。我需要它来返回每个值。
我正在为 Python 3 编写这个类,并且我正在使用 re.groups() 来拆分行。
我正在提供输入文件、控制台输出和类的代码。
输入文件:
City = "Urban Recovery", "Urban Mop-up Operation", "The Oncoming Darkness", "Arks Ship Fire Swirl"
Forest = "Subdue Fang Banther", "With Wind and Rain"
Caves = "Cave", "Volcanic Guerillas"
Desert = "Desert Guerillas"
Tundra =
Skyland = "Rampaging Malice", "Chrome"
Tunnels = "Mega Mecha awakening"
Ruins = 
Coast = "Beach Wars!"
Quarry = 
Space = "Profound Darkness' Kin: Elder", "Raging Dark Arms", "Approaching Dark Arms", "Utterly Profound", "Falz", "Dark Falz"
Event = "Merry Christmas on Ice", "Trick or Treat", "A Boisterous White Day", "Where's the Chocolate"
控制台输出:
('City', 'Urban Recovery', 'Arks Ship Fire Swirl') <class 'tuple'>
('Forest', 'Subdue Fang Banther', 'With Wind and Rain') <class 'tuple'>
('Caves', 'Cave', 'Volcanic Guerillas') <class 'tuple'>
('Desert', 'Desert Guerillas', None) <class 'tuple'>
('Skyland', 'Rampaging Malice', 'Chrome') <class 'tuple'>
('Tunnels', 'Mega Mecha awakening', None) <class 'tuple'>
('Coast', 'Beach Wars!', None) <class 'tuple'>
('Space', "Profound Darkness' Kin: Elder", 'Dark Falz') <class 'tuple'>
代码:
import re
class QuestSelector:
    def __init__(self, filename):
        self.quests = []
        self.filename = filename
        self.parser = re.compile("^([A-Z_]*)[ \t]*=[ \t]*\"([A-Z\:0-9\'\-\! ]*)\"(?:,[ \t]*\"([A-Z\:0-9\'\-\! ]*)\")*$", re.I)
        self.Load()
    def Load(self):
        try:
            file = open(self.filename)
            for line in file.readlines():
                grp = self.parser.match(line[:-1])
                if (grp):
                    tup = grp.groups()
                    print("{} {}".format(tup, str(type(tup))))
        except IOError:
            print("Could not read {}.".format(file))
        except FileNotFoundError:
            print("Could not open {}.".format(file))
    def Available(self):
        print(self.quests)
    def criticalError(self, code):
            print("This was a critical error, will now exit({})".format(code))
            exit(code)
感谢您的帮助。