如何使用正则表达式提取特定文本

时间:2014-04-21 16:21:46

标签: javascript regex

以下是我用于在输入字符串上应用正则表达式以提取2个组的代码,即百分比和颜色。

    var variable = "#clasemedia[ percentage <= 100] { polygon-fill: #B20026;} #clasemedia [ percentage <= 74] { polygon-fill: #DE181D; } #clasemedia [ percentage <= 66] { polygon-fill: #EF3323; }#clasemedia [ percentage <= 60] { polygon-fill: #FC532B; }#clasemedia [ percentage <= 55] { polygon-fill: #FD7636; }#clasemedia [ percentage <= 50] { polygon-fill: #FD9740; }#clasemedia [ percentage <= 47] { polygon-fill: #FEAD4A; }#clasemedia [ percentage <= 45] { polygon-fill: #FEC25D; }#clasemedia [ percentage <= 41] { polygon-fill: #FEDA77; }#clasemedia [ percentage <= 36] { polygon-fill: #FFF9A9; }"
    pollo = variable.match(/(#\w+\s*\[\s+(\w+\s+\<\=\s+\w+)\]\s+\{[\s+\w-\w\:#\w;]+\})/g)
    for(i=0; i<pollo.length; i++){
        promedio = pollo[i].match(/\[\s+(\w+\s+\<\=\s+\d[0-9]+)\]\s/g)
        color = pollo[i].match(/\{[\s+\w-\w\:\s+#\w\s+;]+\}/g)
        $("ul").append("<li>percentage  "+promedio+"color "+color+"</li>");

}

上述代码的输出如下:

percentage [ percentage <= 100] color { polygon-fill: #B20026;}
percentage [ percentage <= 74] color { polygon-fill: #DE181D; }

期望的输出:

 percentage 100 color  #B20026

JS小提琴 - http://jsfiddle.net/QR8yB/12/

2 个答案:

答案 0 :(得分:1)

promedio = pollo[i].match(/\[\s+(\w+\s+\<\=\s+\d[0-9]+)\]\s/g).pop().match(/(\d+)/g).pop()
color = pollo[i].match(/\{[\s+\w-\w\:\s+#\w\s+;]+\}/g).pop().match(/#[a-zA-Z0-9]*/g).pop()

你走了。 http://jsfiddle.net/QR8yB/12/ 基本上正则表达式需要改进,当前的正则表达式给你一个数组,因此你看到扭曲了。

percentage 100color #B20026
percentage 74color #DE181D

更好的正则表达式

  • for promedio - (/percentage\s*\<\=\s*(\d*)/g).exec(pollo[i]).pop()
  • 颜色 - pollo[i].match(/#[a-zA-Z0-9]*/g).pop()

或组合
 `

var x  = (/percentage\s*\<\=\s*(\d*).*\.*#([a-zA-Z0-9]*)/g).exec(pollo[i]);
  // gives output ["percentage <= 100] { polygon-fill: #B20026", "100", "B20026"]
  color = x.pop();
  promedio = x.pop();

`

答案 1 :(得分:0)

使用捕获组提取所需的特定部分:

for (i = 0; i < pollo.length; i++) {
    var matches = pollo[i].match(/\[\s+<=\s+(\d+)\]\s+\{\s+\w+-\w+:\s+(#\w+);\}/);
    $("ul").append("<li>percentage " + matches[1] + " color " + matches[2] + "</li>");
}

括号只是百分比数字和颜色表达式。