开发者

JavaScript Regex Only returns one match

开发者 https://www.devze.com 2023-03-21 19:07 出处:网络
I can\'t see where I went wrong here: var TestString = \'+test +\"testing multi\" -not -\"and not this\" \"w00t\" hehe nice +\\\'test this\\\' -\\\'and this as well\\\'\';

I can't see where I went wrong here:

var TestString = '+test +"testing multi" -not -"and not this" "w00t" hehe nice +\'test this\' -\'and this as well\'';
var regex = new Reg开发者_如何学编程Exp('([\\+\\-]{0,1}([\\\'"]).*?\\1|[^\\s]+)', 'g');
var match = regex.exec(TestString);
if (match != null) {
    for (var i = 1; i < match.length; i++) {
        alert('Match ' + i + ': "' + match[i] + '"');
    }
}

For some reason, only +test is matched, followed by an empty match, and that's it.


Well, this seems to work ok

var TestString = '+test +"testing multi" -not -"and not this" "w00t" hehe nice +\'test this\' -\'and this as well\'';
var match = TestString.match(/([+-]?([\\'"]).*?\2|[^\s]+)/gi)
if (match != null) {
    for (var i = 1; i < match.length; i++) {
         alert('Match ' + i + ': "' + match[i] + '"');
    }
}

It wasn't really on purpose... I just rewrote the RegExp to a literal, because I find that easier to read :)

Output

Match 1: "+"testing multi""
Match 2: "-not"
Match 3: "-"and not this""
Match 4: ""w00t""
Match 5: "hehe"
Match 6: "nice"
Match 7: "+'test this'"
Match 8: "-'and this as well'"
0

精彩评论

暂无评论...
验证码 换一张
取 消