JS正则表达式:无法返回数组匹配

时间:2015-07-24 14:39:09

标签: javascript arrays regex

我有一个包含多个输入文本的表单,如:

<div class="width-height">
    <input value="" name="items[1][width]" type="text">
    <br>
    <input value="" name="items[1][height]" type="text">
</div>
 <div class="width-height">
    <input value="" name="items[2][width]" type="text">
    <br>
    <input value="" name="items[2][height]" type="text">
</div>

我尝试使用JS foreach&#34;数字&#34;和&#34;宽度&#34;或者&#34;身高&#34;在一个数组

最佳结果可能性应该是console.log中具有2值的数组:

1,width
1,height
2,width
2,height

我尝试2个正则表达式:

// first: /\d\]\[[a-z]+/i
// second: /\d\]\[\w+/g
$('.width-height > input').each(function () {
    console.log("1 : " + $(this).attr('name').match(/\d\]\[[a-z]+/i));
    console.log("2 : " +  $(this).attr('name').match(/\d\]\[\w+/g));
});

但结果只是:

1 : 1][width
2 : 1][width

我尝试使用取消捕捉设置来排除我不需要的部分:

console.log("3 : " +  $(this).attr('name').match(/(?:\w+\[)\d(?:\]\[)\w+/g));

但它只返回1个字符串

3 : items[1][width

我想我不会理解正则表达式中的某些东西..非捕获和&#34; g&#34;标志我认为它应该返回所有可能性而不捕获并构建一个具有检索值的数组但是..不是..: - /

Tranks的帮助!

4 个答案:

答案 0 :(得分:3)

非捕获组不会从整场比赛中排除任何数据,它只是不会出现在捕获的组列表中。

您需要使用捕获组来处理此问题(这也意味着您无法使用match)。

捕获组由()分隔。

$('.width-height > input').each(function () {
    var regex = /(\d)\]\[(\w+)/;
    var matches = regex.exec($(this).attr('name'));
    console.log(matches[1] + "," + matches[2]);
});

答案 1 :(得分:1)

尝试这种直接的原生方法:

var inputs = document.querySelectorAll('div.width-height > input[name^="items"]');
var result = [];
var match = null;

Array.prototype.forEach.call(inputs,function(input){
    match = input.name.match(/^items\[(\d)\]\[(width|height)\]$/);
    if(match.length===3)
        result.push([match[1],match[2]]);
});

console.log( result );

你的意思是“数组有2个值”的数组数组吗?如果name属性值的格式不是静态的,那么它只是正则表达式中的一个小变化。或者您是否希望解释您的正则表达式?

答案 2 :(得分:0)

试试这个

$('.width-height > input').each(function () {
    var matches = $(this).attr('name').match(/[\d]?[\w]+/gi);     
    console.log(matches.splice(1));   
});

答案 3 :(得分:0)

如果您对没有jQuery这样做感兴趣,这将返回您所请求输出的数组。

var inputs = document.querySelectorAll("input[type=text]");
var result = Array.prototype.slice.call(inputs).map(function(el){
   return el.getAttribute("name").replace(/.*\[(\d+)\]\[(\w+)\].*$/, "$1,$2");                                      
});
console.log(result);

JSBIN

REGEX