我需要从JSON数据中删除所有
/*...*/
格式的注释。如何使用正则表达式完成呢?以使像这样的字符串值保留:{
"propName": "Hello \" /* hi */ there."
}
保持不变?
在使用回溯控制动词SKIP和FAIL(或一个捕获)之前,您必须先避免所有位于双引号内的内容。
$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);
模式细节:
"(?:[^\\\"]+|\\\.)*+"
" # 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强制模式失败。因此,引用部分将被跳过(并且不能在结果中,因为您在子模式之后使其失败)。
或者您可以使用捕获组,并在替换模式中添加该引用。
/\*(?:[^*]+|\*+(?!/))*+\*/
/\* # 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
\"
的影响,应完全忽略它。 - Desmond Hume\\\{2}
可以被删除,因为它的情况已经被 \\\.
覆盖了吗? - Desmond Hume
"prop0": /* comment */ "Hello"
这种注释不起作用。 - Desmond Hume$code = preg_replace('#/\*(?:.(?!/)|[^\*](?=/)|(?<!\*)/)*\*/#s', '', $code);
- Mihai Iorga/*...*/
的情况下修改该字符串的值。 - Desmond Hume