首页 > 解决方案 > JS Doc字符串的正则表达式匹配描述部分

问题描述

我正在尝试匹配 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 string:,This is second line of description.

标签: node.jsregex

解决方案


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

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,则将其回显到控制台。


推荐阅读