为什么不进行此正则表达式匹配?

我想使用正则表达式来解析它,以仅获取键和值,而不会在字典中包含引号:


def load_replacement_dict(file_name):

    with open(file_name, 'r') as f:

        content = f.read()

        resultDict = {}


        dictionary_regex = re.compile('"([^"]*)" = "([^"]*)"',)


        for result in dictionary_regex.finditer(content):

            resultDict[result.group(1)] = result.group(2)


        for key, value in resultDict.items():

            print (key+" = "+value).decode('utf-8')


        return resultDict

第一个子组匹配,但是当我添加任何内容后,它不再匹配。我尝试使用空格,使用\ s,似乎没有任何内容与等号周围的空格匹配。我在这里想念什么?


编辑:我发现如果我从文件的开头删除unicode字节顺序标记,则正则表达式可以工作。显然不是解决方案,而是关于如何修改正则表达式的线索?


烙印99
浏览 238回答 3
3回答

有只小跳蛙

在我看来,您想要实现的目标可以使用字符串方法而不是正则表达式来轻松实现:>>> s = '"A Key With \"quotes\" in it" = " Another Value "'>>> l,r = [v.strip().strip('"').strip() for v in s.split('=')]>>> l,r ('A Key With "quotes" in it', 'Another Value')转义将被保留,仅由于我创建字符串的方式而在上面丢失了。我从文件中读取了文本,然后发生的是:In [1]: lines = open('x.txt').read().splitlines()In [2]: for s in lines: print [v.strip().strip('"').strip() for v in s.split('=')]   ...: ['Some Key', 'Some Value']['Another Key', 'Another Value']['A Key With \\"quotes\\" in it', 'Another Value']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python