JavaScript Regex:如何将Regex子表达式匹配拆分为多维字符串数组? [英] JavaScript Regex: How to split Regex subexpression matches in to multi-dimensional string arrays?
问题描述
如何将Regex子表达式匹配拆分为多维字符串数组?
我有一个"myvar"字符串:
I have a "myvar" string of:
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
是 QuantityLow-QuantityHigh:PriceEach;
我使用了这个"myreg"正则表达式/(\ d +)[-+](\ d *):(\ d + \.?\ d *);?/g
I used this "myreg" Regex /(\d+)[-+](\d*):(\d+\.?\d*);?/g
与 var myarray = myvar.match(myreg);
:
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"
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"
太棒了!如上所述,除了我需要进一步由Q1-Q2:P分隔的字符串.正则表达式已设置为使用括号标识零件.我认为这可以用一个Regex表达式或至少两个Regex表达式完成,而不是设置某种循环.
Fantastic! Except that I need the strings broken further by the Q1 - Q2 : P as noted above. The regex is already setup to identify the parts with parenthesis. I would think this could be done with a single Regex expression, or at least two, rather than setting up some sort of loop.
感谢您的反馈.
推荐答案
您没有说期望的输出是什么,但是我想这样的输出可能很直观.
You didn't say what the exact output you expect, but I imagine something like this output may be intuitive.
给出:
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 capture all sub-matches is:
var matches = [];
myvar.replace(/(\d+)[-+](\d*):(\d+\.?\d*);?/g, function(m, a, b, c) {
matches.push([a, b, c])
});
(注意:您可以使用[可能更易读的]循环捕获相同的输出):
(Note: you can capture 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 outcome 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"]
这篇关于JavaScript Regex:如何将Regex子表达式匹配拆分为多维字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!