【问题标题】:Remove JSON comments with a regular expression except the one inside strings使用正则表达式删除 JSON 注释,但内部字符串除外
【发布时间】:2021-01-04 03:32:08
【问题描述】:

我想删除 JSON 对象中的所有注释,但字符串中的注释除外。 例如:

{
//Remove this comment
    "Command": "storeSystemConfig",
    "SystemId": "1234", //Remove this comment

        /*Remove this and the empty line above and below*/

/*This can be removed but not what behind here =>*/ "TestParam": "Hello",
    "TestString": "Do not revome this comment /*don not remove*/ and also this one: //Test comment"
}

我现在使用以下正则表达式:

#(\\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|([\s\t]\/.*)|(^\/.*)#

但不幸的是,这个表达式也删除了“TestString”参数中的注释。 在这里你可以看到这个表达式如何处理 JSON 数据:https://regex101.com/r/65VL8v/1,这里是我在工作环境中的 PHP 源代码:https://ideone.com/F4v20p

【问题讨论】:

  • 尽管我喜欢用一行正则表达式解决整个问题,但我不得不承认这很棘手。您是否由于某种原因无法使用多个正则表达式替换?在不同的正则表达式子中删除不同类型的 cmets 会简单得多。
  • 如果它可以通过多行正则表达式或其他 PHP 代码来完成,这也很好。所以回答你的问题,没有特别的理由只用一个正则表达式行。跨度>
  • 我在多行注释问题后修复了单行注释,希望现在可以使用!

标签: php json regex comments preg-replace


【解决方案1】:

这是我的尝试:

<?php
 
$json_origen = <<<'JSON'
{
//Remove this comment
    "Command": "storeSystemConfig", /*1234*/
    "SystemId": "1234", //Remove this comment
 
        /*Remove this and the 
        empty line above and below*/
 
/*This can be removed but not what behind here =>*/ "TestParam": "Hello",
    "TestString": "DNR this comment /*don not remove*/ and also this one: //Test comment" /*4321*/ //1234
}
JSON;
 
//Remove lines with only single line comments
$json = preg_replace("/[\n\r]\s*\/\/.*/", "", $json_origen);
//Remove all lines with only multi line comments
$json = preg_replace("/(?<=[\n\r])\s*\/\*(.[\n\r]?)*?\*\/\s*?/", "", $json);
//Remove lines multi line comments at the end
$json = preg_replace("/(\".+?(?<!\\\\)\"\s*,?)\s*\/\*(.[\n\r]?)*?\*\/\s*?/", "\\1", $json);
//Remove comment at the end of a line
$json = preg_replace("/(\".+?(?<!\\\\)\"\s*,?)\s*\/\/.*?(?=[\n\r])/", '\\1', $json);
//Remove empty lines
$json = preg_replace('/\n\s*\n/', "\n", $json);
 
echo($json);
 
?>

在正常的 JSON 语句之后还有多行 cmets 的问题,但我现在必须编写我的 uni 考试,哈哈,我会尽快更新这个答案。不过,对于示例输入,这应该可以工作。

让我知道您的 JSON 中是否还有其他无关的情况


编辑 1:解决了一个值可能包含双引号的问题,使用负后向 (?&lt;!\\\\),因此转义的双引号不算数

编辑 2: 修复了我谈到的 multi-line-comment-after-normal-json-statements 问题。

编辑 3: 我提供了答案,但没有提供详细的解决方案,所以我在这里使用的概念是积极和消极的后视和前瞻。我也习惯使用[\n\r] 而不仅仅是\n,因为可能会出现其他问题哈哈

编辑 4: 存在一个问题,即如果多行注释后的单行注释位于同一行,则不会删除它们。只需更改正则表达式删除的顺序即可解决此问题。

编辑 5: 修复了 json 语句后的多行注释问题,只需要检查语句后是否有可能的逗号

【讨论】:

  • 感谢您为此解决方案提供多个正则表达式。例如,该示例工作正常,但我发现末尾的多行注释未删除。见:ideone.com/91t5aF
  • 对不起,你已经提到了。我的意思也是 bij 多行 cmets 之后的单行命令。
  • 哦,是的,这是个问题,我应该可以在 10 分钟左右解决这个问题,不便之处敬请见谅!
  • 别抱歉,我对您已经提供的解决方案非常满意,但为了使其完美,请找到一个解决方案,在 JSON 语句之后直接删除多行 cmets。 (请参见本例中的第 6 行 ideone.com/Zx3wdy )注释“/*1234*/”仍在溜走。
  • 我再次编辑了答案,它现在应该可以工作了(我希望)
猜你喜欢
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2011-01-28
  • 1970-01-01
  • 2011-05-13
相关资源
最近更新 更多