0

我试图在所选框发生更改时提醒正则表达式值,选择框具有这样的值

#bla:123#bla2:12345

#bla:122#bla2:12111

#bla:663#bla2:93399

我正在使用 Jquery 获取选择框值,这是我一直在尝试的代码:

 $(document).ready(function() {

     $('#idNrel').change(function()
        {           
            var re = /#.*:(.*)#.*:(.*)/;
            var sourcestring = $('#idNrel').val();
            var results = [];
            var i = 0;
            for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) {

        results[i] = matches;
        for (var j=0; j<matches.length; j++) {
        alert("results["+i+"]["+j+"] = " + results[i][j]);
        }
        i++;
    }


});
});
4

1 回答 1

0

正如elclanrs指出的那样,不需要两个循环,就像matches一组捕获一样。像这样的东西就足够了:

$(document).ready(function () {
    $('#idNrel').change(function () {
        var self = $(this),
            r = /#[^:]+:([^#]+)#[^:]+:(.*)/g, // use global flag
            sourcestring = self.val(),
            matches = r.exec(sourcestring),
            i = 0;
        for (i = 0; i < matches.length; i += 1) {
            // first element in the matches array will be the whole matching string
            // second element in the matches array is the first capture group
            // third element in the matches array is the second capture group
            // this pattern continues, although you have no more capture groups
            alert("Capture " + i + ": = " + matches[i]);
        }
    });
});

而且(当然),一个工作小提琴:http: //jsfiddle.net/Kc4zy/

您可以在此处阅读有关捕获组和 JavaScript 正则表达式的更多信息:

http://www.regular-expressions.info/javascript.html

于 2013-06-01T03:11:24.280 回答