2014-11-24 22 views
0

我想寫一個函數,它接受一個字符串並返回一個包含所有塊註釋內容的數組。例如:如何使用正則表達式從字符串中提取塊註釋?

var text = 'This is not a comment\n/*this is a comment*/\nNot a comment/*Another comment*/'; 
var comments = getComments(text); 

和「評論」將與值的數組:

['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

我更新了你的代碼this jsfiddle,刪除了一些輔助代碼(如串)。這裏是相關的部分:

function getComments(text) { 
    var comments, 
    regex, 
    match; 
    comments = []; 
    regex = /\/\*.*?\*\//g 

    while ((match = regex.exec(text)) != null) { 
     comments.push(match); 
    } 
    return comments; 
} 
+0

這隻適用於* most *但不是所有的情況。以'var a =「/ *」; var b =「* /」;'例如 - 不應該提取任何評論。 – nhahtdh 2014-11-25 02:40:53

1

我不確定JavaScript的片斷,但這個正則表達式應該符合你的模式:\/\*.*?\*\/

相關問題