如何匹配双引号值内的所有双引号?

问题描述 投票:0回答:1

当我试图提高我的正则表达式技能时,我正在尝试解决这个用例。

假设服务器提供了一个格式不正确的 JSON 字符串,我们想要转换该字符串,以便我们可以将其转换为 JSON:

let x = '{"my_text":"hello "world"","test2":"tree","blue":"red "yellow","orange":"green, purple "cyan""}';

我有一个正则表达式,它匹配双引号内的所有双引号,除了

cyan
周围的双引号。

/(?<=\:\"([^\,\"]*))\"(?=([^\,]*)\"\,)/g

如果我是正确的,那是因为

[^\:\"]
排除了
:
"
,而我想从正向后看中按顺序排除它们 (
:"
)。

现在我考虑过在积极的lookbehind之后进行消极的lookbehind,但是它不匹配,我不知道为什么:

/(?<=\:\")(?<!(.*)\:\"(.*))\"(?=([^\,]*)\"\,?)/g`

我错过了什么吗?如何匹配双引号值内的所有双引号?

javascript json regex lookbehind negative-lookbehind
1个回答
0
投票

尽管有评论,我最终还是解决了自己的问题。

let x = '{"my_text":"hello "world"","test2":"tree","blue":"red "yellow","orange":"green, purple "cyan""}';

x = x.replaceAll( /(?<![\,\:\{])\"(?![\:\,\}])/g, '\\"' );

const j = JSON.parse( x );
console.log('j:', j)

结果

© www.soinside.com 2019 - 2024. All rights reserved.