【问题标题】:extract comments with javascript match and/or replace使用 javascript 匹配和/或替换提取评论
【发布时间】:2014-04-14 10:11:26
【问题描述】:

我正在尝试提取 cmets 以使用它们。

如果我有

var a = 'foo';
// this comment should stay here

/* Description: I need to be printed in a section */
/* Usage: I need to be printed in another section 
   and I have multiple lines
*/

预期结果1:

var a = 'foo';
// this comment should stay here

预期结果 2:

Description: I need to be printed in a section

预期结果 3:

Usage: I need to be printed in another section
and I have multiple lines

所以我基本上想要的是 3 个变量

var code = str.replace(regex to remove comments)
var description = str.match(regex to match comments with description)
var usage = str.match(regex to match comments with usage)

我可以根据需要以任何方式格式化 cmets。

顺便说一句。我在一个 grunt 脚本中这样做,以防万一这很重要

var str = grunt.file.read('myfile.filetype')

这是一个实际的例子

@import '../helpers/_prefix';

// MIXIN: .animation-delay
.animation-delay(@values) {
    @vendorPrefixes: -webkit-, -moz-, '';
    @prop: animation-delay;
    // http://caniuse.com/#search=animation
    .prefix();
}


/* Description: Defines the delay of an animation */


/* // Usage: 
  .animation-delay(200ms)
*/

我还希望删除 /**/

代码块应该输出

@import '../helpers/_prefix';

// MIXIN: .animation-delay
.animation-delay(@values) {
    @vendorPrefixes: -webkit-, -moz-, '';
    @prop: animation-delay;
    // http://caniuse.com/#search=animation
    .prefix();
}

最后一个(Usage)应该是输出

// Usage
.animation-delay(200ms)

.animation-delay(200ms)

【问题讨论】:

  • 嵌套 cmets 怎么样?
  • 嗯?我不需要嵌套的 cmets。我正在为我编写的库编写文档,并希望直接从文件中提取信息。所以我可以根据需要为 cmets 设置样式。我真的不擅长正则表达式。

标签: javascript regex comments


【解决方案1】:

你可以这样做:

m = str.match(/\/\/.*/g);
var code = m ? m[0] : "";

m = str.match(/\/\*.*?Description: *([\s\S]*?)\*\//);
var description = m ? m[1] : "";

m = str.match(/\/\*.*?Usage: *([\s\S]*?)\*\//);
var usage = m ? m[1] : "";

【讨论】:

  • 似乎没有按预期工作。我用“实际”用例更新了问题
  • 看起来更好,但“代码”部分只返回第一条注释行// MIXIN: .animation-delay。其他两个似乎工作得很好。我想剥离所有 C cmets 并保留未嵌套在其他 cmets 中的 C# cmets 是有意义的。如果需要,也可以删除嵌套的 cmets 并用其他符号替换
猜你喜欢
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 2012-05-10
相关资源
最近更新 更多