gpt4 book ai didi

javascript - JSON 上的正则表达式替换正在从数组中删除一个对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:57 25 4
gpt4 key购买 nike

我正在努力提高我对 Regex 的理解,但是这个让我很困惑。我从一些定义为的文本开始:

var txt = "{\"columns\":[{\"text\":\"A\",\"value\":80},{\"text\":\"B\",\"renderer\":\"gbpFormat\",\"value\":80},{\"text\":\"C\",\"value\":80}]}";

并按如下方式进行替换:

txt.replace(/\"renderer\"\:(.*)(?:,)/g,"\"renderer\"\:gbpFormat\,");

结果是:

"{"columns":[{"text":"A","value":80},{"text":"B","renderer":gbpFormat,"value":80}]}"

我希望 renderer 属性值的引号被删除;这已经发生了,而且 C 列也完全丢失了!我真的很想有人解释我的正则表达式如何删除 C 列?

作为额外的奖励,如果您能解释如何删除 renderer 任何值周围的引号(即这样我就不必在正则表达式中对值 gbpFormat 进行硬编码)那'太棒了。

最佳答案

您正在使用贪婪 运算符,而您需要一个惰性 运算符。改变这个:

"renderer":(.*)(?:,)
^---- add here the '?' to make it lazy

"renderer":(.*?)(?:,)

Working demo

enter image description here

您的代码应该是:

txt.replace(/\"renderer\"\:(.*?)(?:,)/g,"\"renderer\"\:gbpFormat\,");

如果你正在学习正则表达式,看看这个 documentation了解更多关于贪婪的知识。理解这一点的一个很好的摘录是:

Watch Out for The Greediness!

Suppose you want to use a regex to match an HTML tag. You know that the input will be a valid HTML file, so the regular expression does not need to exclude any invalid use of sharp brackets. If it sits between sharp brackets, it is an HTML tag.

Most people new to regular expressions will attempt to use <.+>. They will be surprised when they test it on a string like This is a first test. You might expect the regex to match and when continuing after that match, .

But it does not. The regex will match first. Obviously not what we wanted. The reason is that the plus is greedy. That is, the plus causes the regex engine to repeat the preceding token as often as possible. Only if that causes the entire regex to fail, will the regex engine backtrack. That is, it will go back to the plus, make it give up the last iteration, and proceed with the remainder of the regex.

Like the plus, the star and the repetition using curly braces are greedy.

关于javascript - JSON 上的正则表达式替换正在从数组中删除一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26769306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com