为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

烙印99 2021-03-29 16:13:41
我想使用正则表达式来解析它,以仅获取键和值,而不会在字典中包含引号: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字节顺序标记,则正则表达式可以工作。显然不是解决方案,而是关于如何修改正则表达式的线索?
查看完整描述

3 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

在我看来,您想要实现的目标可以使用字符串方法而不是正则表达式来轻松实现:


>>> 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']


查看完整回答
反对 回复 2021-04-02
  • 3 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号