JS Doc字符串的正则表达式匹配描述部分

时间:2019-05-06 14:30:38

标签: node.js regex

我正在尝试匹配JS文档字符串的描述部分(无@符号的行)。这是几个文档字符串示例。

/**
 * This is a doc string
 * @param withArg description of withArg
 * @param withArg2 description of withArg2
 */

/**
 * This is an other doc string
 * This is second line of description.
 */

这似乎在正则表达式编辑器中起作用: /\*\S*(.*?)(@)/ 参见:https://regexr.com/4dfbn

但是在javascript中: https://jsbin.com/qekisogula/1/edit?html,js,console

有什么想法吗?

非常感谢

更新: 预期输出

示例1: This is an other doc string

示例2: This is an other doc stringThis is second line of description.

1 个答案:

答案 0 :(得分:1)

我实际上会采用逐行读取文件并使用一些基本解析逻辑的方法:

var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('file.in')
});

var start = false;

lineReader.on('line', function (line) {
    if (line.startsWith("/**") {
        start = true;
    }
    else if (line.startsWith("*/")) {
        start = false;
    }
    else if (start && !line.includes("@param")) {
        console.log("doc string: ", line);
    }
});

这里的逻辑是我们使用布尔标志start来跟踪我们是否在带有文档字符串的注释中。当击中/**时,标志打开,当击中*/时,标志关闭。如果遇到不包含@param的行,则将其回显到控制台。