gpt4 book ai didi

javascript - 正则表达式在 JS 文件中查找第一条评论

转载 作者:行者123 更新时间:2023-12-02 06:39:24 25 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式(用 JavaScript)来匹配 JS 文件开头的多行注释。

到目前为止,我想到了这个:/^(\/\*[^\*\/]*\*\/)/g

它适用于单行注释:http://refiddle.com/24o
但我的问题是它不适用于多行注释:http://refiddle.com/24m

你有什么解决办法吗?

最佳答案

HTML , JavaScript 不能被正则表达式解析。尝试正确地这样做是徒劳的。

相反,您必须使用能够将 JavaScript 源代码正确转换为 AST 的解析器,您可以通过编程方式检查它。幸运的是,有图书馆 do the parsing for you .

Here's a working example that outputs the AST of this code:

/* this is a
multi-line
comment */

var test = "this is a string, /* and this is not a comment! */";

// ..but this is

这让我们:

[
"toplevel",
[
[
{
"name": "var",
"start": {
"type": "keyword",
"value": "var",
"line": 5,
"col": 4,
"pos": 57,
"endpos": 60,
"nlb": true,
"comments_before": [
{
"type": "comment2",
"value": " this is a\n multi-line\n comment ",
"line": 1,
"col": 4,
"pos": 5,
"endpos": 47,
"nlb": true
}
]
},
"end": {
"type": "punc",
"value": ";",
"line": 5,
"col": 67,
"pos": 120,
"endpos": 121,
"nlb": false,
"comments_before": []
}
},
[
[
"test",
[
{
"name": "string",
"start": {
"type": "string",
"value": "this is a string, /* and this is not a comment! */",
"line": 5,
"col": 15,
"pos": 68,
"endpos": 120,
"nlb": false,
"comments_before": []
},
"end": {
"type": "string",
"value": "this is a string, /* and this is not a comment! */",
"line": 5,
"col": 15,
"pos": 68,
"endpos": 120,
"nlb": false,
"comments_before": []
}
},
"this is a string, /* and this is not a comment! */"
]
]
]
]
]
]

现在只需遍历 AST 并提取您需要的内容即可。

关于javascript - 正则表达式在 JS 文件中查找第一条评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11141283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com