JavaScript Regex: how to split a Regex subexpression matches multidimensional string arrays?

How would you split up a Regex subexpression in multidimensional string arrays?

I have the string "myvar":

1-4:2;5-9:1.89;10-24:1.79;25-99:1.69;100-149:1.59;150-199:1.49;200-249:1.39;250+:1.29

which is a repetition QuantityLow - QuantityHigh : PriceEach ;

I used this "myreg" Regex /(\d+)[-+](\d*):(\d+\.?\d*);?/g

Used with var myarray = myvar.match(myreg);

which produced:

myarray[0] = "1-4:2;"


myarray[1] = "5-9:1.89;"


myarray[2] = "10-24:1.79;"


myarray[3] = "25-99:1.69;"


myarray[4] = "100-149:1.59;"


myarray[5] = "150-199:1.49;"


myarray[6] = "200-249:1.39;"


myarray[7] = "250+:1.29"


Fantastic! Except that I need the lines broken further Q1-Q2: P as above. The regex is already set up to identify the parenthesized parts. I would have thought it could be done with one Regex expression, or at least two, instead of setting up some kind of loop.

Thanks for the feedback.

+2


source to share


3 answers


You didn't say what exact result you expect, but I think that something like this output might be intuitive.

Given:

var myvar = "1-4:2;5-9:1.89;10-24:1.79;25-99:1.69;100-149:1.59;150-199:1.49;200-249:1.39;250+:1.29";

      

A quick way to grab all sub matches:

var matches = [];
myvar.replace(/(\d+)[-+](\d*):(\d+\.?\d*);?/g, function(m, a, b, c) {
    matches.push([a, b, c])
});

      



(Note: you can write the same output with a [potentially more readable] loop):

var myreg = /(\d+)[-+](\d*):(\d+\.?\d*);?/g;
var matches = [];
while(myreg.exec(myvar)) {
    matches.push([RegExp.$1, RegExp.$2, RegExp.$3])
}

      

Either way, the result is an array of matches:

matches[0]; // ["1", "4", "2"]
matches[1]; // ["5", "9", "1.89"]
matches[2]; // ["10", "24", "1.79"]
matches[3]; // ["25", "99", "1.69"]
matches[4]; // ["100", "149", "1.59"]
matches[5]; // ["150", "199", "1.49"]
matches[6]; // ["200", "249", "1.39"]
matches[7]; // ["250", "", "1.29"]

      

+8


source


var r = /(\d+)[-+](\d*):(\d+\.?\d*);?/g;
var s = "1-4:2;5-9:1.89;10-24:1.79;25-99:1.69;100-149:1.59;150-199:1.49;200-249:1.39;250+:1.29";
var match;
while ((match = r.exec(s)) != null) {
  console.log("From " + match[1] + " to " + match[2] + " is " + match[3]);
}

      

The call console.log()

is a call to Firefox / Firebug. You can of course use alert()

, document.write()

or whatever.



See the reference to the RegExp object , in particular RegExp methods , most notably RegExp.exec()

.

+2


source


The easiest way to do this is using the split String method:

var myvar = "1-4:2;5-9:1.89;10-24:1.79;25-99:1.69;100-149:1.59;150-199:1.49;200-249:1.39;250+:1.29";
myvar.split(';');

      

which produced:

["1-4:2", "5-9:1.89", "10-24:1.79", "25-99:1.69", "100-149:1.59", "150-199:1.49", "200-249:1.39", "250+:1.29"]

      

0


source







All Articles