How to extract a specific text with regex

advertisements

Here is the code that I used to apply regex on the input string to extract 2 groups, namely percentage and color.

    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>");

}

The output of the aforementioned code is the following:

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

Desired Output:

 percentage 100 color  #B20026

JS Fiddle - http://jsfiddle.net/QR8yB/12/


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()

Here you go. http://jsfiddle.net/QR8yB/12/ Basically the regex needs to be improved, the current one gives you an array, hence you see the distorted out.

percentage 100color #B20026
percentage 74color #DE181D

Better Regexes

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

Or Combined
`

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();

`