用于删除js中的/ ** /注释的正则表达式

时间:2014-03-28 20:39:05

标签: javascript regex

如何在JavaScript中使用正则表达式从字符串中删除类似的内容?

/*
    multi-line comment
*/

这就是我的尝试:

var regex = /(\/\*(^\*\/)*\*\/)/g;
string = string.replace(regex, '');

3 个答案:

答案 0 :(得分:3)

如果您想匹配/*后跟任意数量的不包含*/的文字,后跟*/,那么您可以使用正则表达式,但它会正确删除JavaScript中的块注释。

我描述的模式失败的一个简单示例是:

var a = '/*'; /* block comment */

请注意,即使第一个/*包含在字符串中,它也会匹配。如果您可以保证您在其中搜索的内容不包含此类不一致,或者只是使用正则表达式来查找要进行手动更改的位置,那么您应该相当安全。否则,不要使用正则表达式,因为在这种情况下它们是错误的工作工具; 你被警告


要构建正则表达式,您只需将我的第一句话分解为其复合部分。

  • /启动正则表达式文字
  • \/\*与文字字符/*
  • 相匹配
  • [\s\S]*?以非贪婪的方式匹配任何字符
  • \*\/与文字字符*/
  • 相匹配
  • /结束正则表达式

总之,你最终得到:

/\/\*[\s\S]*?\*\//

非贪婪匹配是必要的,以防止在多个块注释位于文件中时捕获关闭注释(*/):

/* foo */
var foo = 'bar';
/* fizz */
var fizz = 'buzz';

使用非贪婪匹配,

/* foo */

/* fizz */

将匹配,没有非贪婪的匹配,

/* foo */
var foo = 'bar';
/* fizz */

会匹配。

答案 1 :(得分:3)

在几种情况下,使用正则表达式的所有答案都完全失败:

var myString = '/*Hello World!*/'; // inside a string
var a = "/*b", c = /.*/g; // inside a string partially, and inside a regex literal

// /*
alert("This will not fire with the regular expressions, but works in JS");
// */
var/**/b = 5; // perfectly valid, replacing a comment with nothing is simply incorrect

对于一些比较明显的人。正则表达式不够强大,无法正确解析注释,他们需要了解语言语法。

所以,正则表达式失败了,还剩下什么?解析器。难吗?不是真的。

让我们自己看一下JavaScript语法吧! section on comments州:

MultiLineComment ::
    /* MultiLineCommentCharsopt */

这很好,这意味着当我们进入多行注释时,我们不会退出它,直到我们到达*/然后我们立即退出它。

但什么时候可以发表评论?几乎在文字之外的任何地方。在我们所拥有的5个文字中,多行注释标记只能出现在字符串文字和正则表达式文字中。

function parse(code){
    // state
    var isInRegExp = false;
    var isInString = false;
    var terminator = null; // to hold the string terminator
    var escape = false; // last char was an escape
    var isInComment = false;

    var c = code.split(""); // code

    var o = []; // output
    for(var i = 0; i < c.length; i++){
        if(isInString) {  // handle string literal case
             if(c[i] === terminator && escape === false){
                  isInString = false;
                  o.push(c[i]);
             } else if (c[i] === "\\") { // escape
                  escape = true;
             } else {
                  escape = false;
                  o.push(c[i]); 
             }
        } else if(isInRegExp) { // regular expression case
             if(c[i] === "/" && escape === false){
                 isInRegExp = false;
                 o.push(c[i]);
             } else if (c[i] === "\\") {
                 escape = true;
             } else { 
                escape = false;
                o.push(c[i]);
             }
        } else if (isInComment) { // comment case
              if(c[i] === "*" && c[i+1] === "/"){
                  isInComment = false;
                  i++;
                  // Note - not pushing comments to output
              }
        } else {   // not in a literal
              if(c[i] === "/" && c[i+1] === "/") { // single line comment
                   while(c[i] !== "\n" && c[i] !== undefined){ //end or new line
                       i++;
                   }
              } else if(c[i] === "/" && c[i+1] === "*"){ // start comment
                    isInComment = true;
                    o.push(" "); // add a space per spec
                    i++; // don't catch /*/
              } else if(c[i] === "/"){ // start regexp literal
                    isInRegExp = true;
                    o.push(c[i]);
              } else if(c[i] === "'" || c[i] === '"'){ // string literal
                    isInString = true;
                    o.push(c[i]);
                    separator = c[i];
              } else { // plain ol' code
                    o.push(c[i]);
              }
        }
    }
    return o.join("");
}

我刚刚在控制台中写了这个,很长 - 但你能看出它有多简单吗?这在概念上非常简单 - 它只是跟踪代码中的位置,并基于消耗这个词。

我们试一试:

parse("var a = 'hello world'"); // var a = 'hello world' 
parse("var/**/a = 'hello world'"); // var a = 'hello world' 
parse("var myString = '/*Hello World!*/';"); // var myString = '/*Hello World!*/';
parse('var a = "/*b", c = /.*/g;'); // var a = "/*b", c = /.*/g;
parse("var a; /* remove me please! */"); // var a;
parse("var x = /* \n \n Hello World Multiline String \n \n */ 5"); // var x =   5 

答案 2 :(得分:-1)

以下将从Javascript中删除命令和垃圾邮件。

 var regex = /^(\s*[^\s]*\s*)$/g;
 string = string.replace(regex, '');

希望这会有所帮助......

相关问题