我正试图构造一个正则表达式来删除javascript代码中的所有注释,这两行代码都是(//.)和多行(/*.*/)。这就是我想出来的:
/\"[^\"]*\"|'[^']*'|(\/\/.*$|\/\*[^\*]*\*\/)/mg描述:正如您所看到的,它还搜索字符串文本。这是因为字符串文本可以包含与注释模式相匹配的内容(例如: location.href = "http://www.domain.com";将匹配为单行注释)。因此,我将字符串文本模式放在替代模式中的第一位。下面是两种模式,分别用于捕获单行注释和多行注释。这些内容包含在同一个捕获组中,因此我可以使用string.replace(模式,"")删除注释。
我已经用几个js-文件测试了这个表达式,它似乎正在工作。我的问题是,我是否应该寻找其他模式,或者是否还有其他需要考虑的问题(例如,如果在某些浏览器中对正则表达式或替代实现的支持有限,则需要考虑)。
发布于 2015-03-10 21:50:10
使用C/C++风格的注释脱衣舞。
下面的regex做这些事情
regex有两个窗体来进行格式保存:
\h和换行符\n构造[ \t]和\r?\n构造这些标志是多行和全局的。
替代者为捕获组2,$2或\2。
表格1:
raw: ((?:(?:^\h*)?(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(?:\h*\n(?=\h*(?:\n|/\*|//)))?|//(?:[^\\]|\\\n?)*?(?:\n(?=\h*(?:\n|/\*|//))|(?=\n))))+)|("(?:\\[\S\s]|[^"\\])*"|'(?:\\[\S\s]|[^'\\])*'|[\S\s][^/"'\\\s]*)
delimited: /((?:(?:^\h*)?(?:\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/(?:\h*\n(?=\h*(?:\n|\/\*|\/\/)))?|\/\/(?:[^\\]|\\\n?)*?(?:\n(?=\h*(?:\n|\/\*|\/\/))|(?=\n))))+)|("(?:\\[\S\s]|[^"\\])*"|'(?:\\[\S\s]|[^'\\])*'|[\S\s][^\/"'\\\s]*)/mg 表格2:
raw: ((?:(?:^[ \t]*)?(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(?:[ \t]*\r?\n(?=[ \t]*(?:\r?\n|/\*|//)))?|//(?:[^\\]|\\(?:\r?\n)?)*?(?:\r?\n(?=[ \t]*(?:\r?\n|/\*|//))|(?=\r?\n))))+)|("(?:\\[\S\s]|[^"\\])*"|'(?:\\[\S\s]|[^'\\])*'|(?:\r?\n|[\S\s])[^/"'\\\s]*)
delimited: /((?:(?:^[ \t]*)?(?:\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/(?:[ \t]*\r?\n(?=[ \t]*(?:\r?\n|\/\*|\/\/)))?|\/\/(?:[^\\]|\\(?:\r?\n)?)*?(?:\r?\n(?=[ \t]*(?:\r?\n|\/\*|\/\/))|(?=\r?\n))))+)|("(?:\\[\S\s]|[^"\\])*"|'(?:\\[\S\s]|[^'\\])*'|(?:\r?\n|[\S\s])[^\/"'\\\s]*)/mg表格2的扩展(用这格式)版本:
( # (1 start), Comments
(?:
(?: ^ [ \t]* )? # <- To preserve formatting
(?:
/\* # Start /* .. */ comment
[^*]* \*+
(?: [^/*] [^*]* \*+ )*
/ # End /* .. */ comment
(?: # <- To preserve formatting
[ \t]* \r? \n
(?=
[ \t]*
(?: \r? \n | /\* | // )
)
)?
|
// # Start // comment
(?: # Possible line-continuation
[^\\]
| \\
(?: \r? \n )?
)*?
(?: # End // comment
\r? \n
(?= # <- To preserve formatting
[ \t]*
(?: \r? \n | /\* | // )
)
| (?= \r? \n )
)
)
)+ # Grab multiple comment blocks if need be
) # (1 end)
| ## OR
( # (2 start), Non - comments
"
(?: \\ [\S\s] | [^"\\] )* # Double quoted text
"
| '
(?: \\ [\S\s] | [^'\\] )* # Single quoted text
'
| (?: \r? \n | [\S\s] ) # Linebreak or Any other char
[^/"'\\\s]* # Chars which doesn't start a comment, string, escape,
# or line continuation (escape + newline)
) # (2 end)发布于 2019-12-02 22:21:51
import prettier from 'prettier';
function decomment(jsCodeStr) {
const options = { printWidth: 160, singleQuote: true, trailingComma: 'none' };
// actually strip comments:
options.parser = (text, { babel }) => {
const ast = babel(text);
delete ast.comments;
return ast;
};
return prettier.format(jsCodeStr, options);
}发布于 2015-03-10 14:12:15
看看这段代码。尽管这是针对PHP的,但我认为这种模式是正确的。您可以为JavaScript调整模式。
https://stackoverflow.com/questions/28963501
复制相似问题