【发布时间】:2015-01-08 16:30:36
【问题描述】:
我有一个硬件设备,它通过带有 json 字符串的 http 进行控制,但已知它返回的 json 是无效的。在 Python 中,我可以修复它
response = """[
{text: "67239961", selected: "true", value: "67239961"}
];"""
p = re.compile('([a-zA-Z_]+):')
joined = "".join(response.splitlines())
stripped = joined.strip(';')
cleaned = p.sub(r'"\1":', stripped)
>> [{"text": "67239961", "selected": "true", "value": "67239961"}]
不过,我需要在 C Sharp 中执行此操作,并且对它的 Regex 实现不够熟悉。我试图直接将其移植为
string[] split = response.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
string joined = String.Join("", split);
string stripped = joined.Trim(';');
Regex re = new Regex(@"([a-zA-Z_]+):");
string cleaned = re.Replace(stripped, @"\1");
>> [{\1 "67239961", \1 "true", \1"67239961"}]
实现这一点的正确模式是什么?
编辑:修复是
string cleaned = re.Replace(stripped, @"""$1"":");
【问题讨论】:
-
我对C#中的正则表达式不熟悉,但是你可以尝试使用
$1而不是\1。 -
感谢您的评论,留下了文字,但删除了冒号。我也改成 Regex re = new Regex(@"\([a-zA-Z_]+\):");并且它保持与开始时相同的状态