我想编写一个函数,它接受一个字符串并返回一个数组,其中包含来自它的所有块注释的内容。例如:
var text = 'This is not a comment\n/*this is a comment*/\nNot a comment/*Another comment*/';
var comments = getComments(text);
'comments'将是一个包含值的数组:
['this is a comment', 'Another comment']
我尝试使用此代码:
function getComments(text) {
var comments,
comment,
regex;
comments = [];
regex = /\/\*([^\/\*]*)\*\//g;
comment = regex.exec(text);
while(comment !== null) {
skewer.log(comment);
comments.push(comment[1]);
comment = regex.exec(text);
}
return comments;
}
问题是如果评论中有*或 / ,则不匹配
答案 0 :(得分:1)
我不确定JavaScript部分,但这个正则表达式应该符合您的模式:\/\*.*?\*\/
答案 1 :(得分:0)
我在this jsfiddle中更新了一些代码,删除了一些辅助代码(如skewer)。以下是相关部分:
function getComments(text) {
var comments,
regex,
match;
comments = [];
regex = /\/\*.*?\*\//g
while ((match = regex.exec(text)) != null) {
comments.push(match);
}
return comments;
}
答案 2 :(得分:0)