【发布时间】:2012-10-25 18:16:55
【问题描述】:
我的输入看起来像一个参数列表:
input1 = '''
title="My First Blog" author='John Doe'
'''
值可以用单引号或双引号括起来,但是也允许转义:
input2 = '''
title='John\'s First Blog' author="John Doe"
'''
有没有办法使用正则表达式来提取单引号或双引号以及转义引号的键值对?
使用python,我可以使用以下正则表达式并处理非转义引号:
rex = r"(\w+)\=(?P<quote>['\"])(.*?)(?P=quote)"
然后返回:
import re
re.findall(rex, input1)
[('title', '"', 'My First Blog'), ('author', "'", 'John Doe')]
和
import re
re.findall(rex, input2)
[('title', "'", 'John'), ('author', '"', 'John Doe')]
后者不正确。我不知道如何处理转义的引号——假设在 (.*?) 部分。我一直在使用Python regex to match text in single quotes, ignoring escaped quotes (and tabs/newlines) 上发布的答案中的解决方案,但无济于事。
从技术上讲,我不需要 findall 来返回引号字符——而只是键/值对——但这很容易处理。
任何帮助将不胜感激!谢谢!
【问题讨论】: