【问题标题】:Javascript regex unexpected outputJavascript 正则表达式意外输出
【发布时间】:2015-07-06 08:45:44
【问题描述】:

我正在尝试使用 node 对 css 文件执行一些 regex

这是我的 javascript:

var fs = require ('fs');

fs.readFile('test.css','utf8',function(error,css){
if(error){
    console.log("I'm sorry, something went terribly wrong :o Here's the message: "+error);
}



var matches = css.match(/([a-zA-Z-]+):\s*([0-9]+)(vh|VH|vw|VW)/g);

    console.log(matches[2][1]);



});

运行时的预期输出:

实际输出:

正如你所看到的,它并没有像预期的那样将每个匹配项都放在自己的数组中,它只是将所有内容放在一个没有任何子数组的巨型数组中。 有什么我能做的吗?

【问题讨论】:

  • 在我看来像一个数组...
  • 每个匹配项也应该是一个数组,而不是字符串
  • 匹配按预期工作。如果您没有专门处理它们,它会忽略捕获组。您要么必须使用不同的方法,要么将匹配捕获组保存在某些循环中。
  • 感谢您的提示 :)

标签: javascript arrays regex node.js


【解决方案1】:

match 在这种情况下不会给你详细的匹配结果:

如果正则表达式包含 g 标志,则该方法返回一个包含所有匹配子字符串而不是匹配对象的数组。

您可以改用exec

var regex = /([a-zA-Z-]+):\s*([0-9]+)(vh|VH|vw|VW)/g;
var css = "body{\nfont-size: 10vw;\n height: 500vh\n}";
var match;

while (match = r.exec(css)){
    console.log(match)
}

这给出了这个输出:

["font-size: 10vw", "font-size", "10", "vw", index: 6, input: "body{↵font-size: 10vw;↵ height: 500vh↵}"]  
["height: 500vh", "height", "500", "vh", index: 24, input: "body{↵font-size: 10vw;↵ height: 500vh↵}"]

【讨论】:

    【解决方案2】:
    var reg = /([a-zA-Z-]+):\s*([0-9]+)(vh|VH|vw|VW)/g;
    var matches = [];
    var m;
    
    while ((m = reg.exec(css)) !== null) {
        if (m.index === reg.lastIndex) {
            reg.lastIndex++;
        }
        matches.push(m);
    }
    
    console.log(matches);
    

    【讨论】:

      【解决方案3】:

      这实际上是预期的行为。如果您使用带有全局标志的string.match 方法,括号不会在匹配项中创建组:

      var str = "javascript is cool";
      var result = str.match( /JAVA(SCRIPT)/g );
      console.log( result[0] ); // javascript
      console.log( result.length ); //1
      

      您的案例正在使用regexp.exec(str)。它可以在其中找到所有匹配项和括号组。

      var str = 'javascript is cool. Use javascript';
      
      var regexp = /java(script)/g;
      
      while (result = regexp.exec(str)) {   
        console.log(result.length);   //2
        console.log(result[0]);  //javascript
        console.log(result[1]);  //script 
      } 
      

      【讨论】:

      • 感谢您的提示 :)
      【解决方案4】:

      根据以上答案,我设法想出了以下代码:

      while(match = css.match(/([a-zA-Z-]+):\s*([0-9]+)(vh|VH|vw|VW)/)){
              matches.push(match);
              css = css.replace(match[0],'');
      }
      

      非常感谢大家的帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-19
        • 1970-01-01
        • 2015-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多