从JSON数据中删除注释 [英] Remove comments from JSON data

查看:1546
本文介绍了从JSON数据中删除注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从JSON数据中删除所有/*...*/样式注释.我该如何使用正则表达式来实现这样的字符串值

I need to remove all /*...*/ style comments from JSON data. How do I do it with regular expressions so that string values like this

{
    "propName": "Hello \" /* hi */ there."
}

保持不变吗?

推荐答案

您必须首先使用回溯控制动词 SKIP FAIL (或捕获)

You must first avoid all the content that is inside double quotes using the backtrack control verbs SKIP and FAIL (or a capture)

$string = <<<'LOD'
{
    "propName": "Hello \" /* don't remove **/ there." /*this must be removed*/
}
LOD;

$result = preg_replace('~"(?:[^\\\"]+|\\\.)*+"(*SKIP)(*FAIL)|/\*(?:[^*]+|\*+(?!/))*+\*/~s', '',$string);

// The same with a capture:

$result = preg_replace('~("(?:[^\\\"]+|\\\.)*+")|/\*(?:[^*]+|\*+(?!/))*+\*/~s', '$1',$string);

模式详细信息:

"(?:[^\\\"]+|\\\.)*+"

这部分描述了引号内的可能内容:

This part describe the possible content inside quotes:

"              # literal quote
(?:            # open a non-capturing group
    [^\\\"]+   # all characters that are not \ or "
  |            # OR
    \\\.)*+    # escaped char (that can be a quote)
"

然后您可以使此子模式失败,并显示(*SKIP)(*FAIL)(*SKIP)(?!).如果此后模式失败,则 SKIP 会在此点之前禁止回溯. FAIL 强制模式失败.因此,带引号的部分将被跳过(并且在结果中不会出现,因为之后会使子模式失败).

Then You can make this subpattern fails with (*SKIP)(*FAIL) or (*SKIP)(?!). The SKIP forbid the backtracking before this point if the pattern fails after. FAIL forces the pattern to fail. Thus, quoted part are skipped (and can't be in the result since you make the subpattern fail after).

或者您使用捕获组,并在替换模式中添加参考.

Or you use a capturing group and you add the reference in the replacement pattern.

/\*(?:[^*]+|\*+(?!/))*+\*/

这部分描述注释中的内容.

This part describe content inside comments.

/\*           # open the comment
(?:           
    [^*]+     # all characters except *
  |           # OR
    \*+(?!/)  # * not followed by / (note that you can't use 
              # a possessive quantifier here)
)*+           # repeat the group zero or more times
\*/           # close the comment

仅当反斜杠在引号内的换行符之前使用s修饰符.

The s modifier is used here only when a backslash is before a newline inside quotes.

这篇关于从JSON数据中删除注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆