【发布时间】: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