gpt4 book ai didi

JavaScript Regex 只返回一个匹配项

转载 作者:行者123 更新时间:2023-11-29 20:15:53 24 4
gpt4 key购买 nike

我看不出哪里出错了:

var TestString = '+test +"testing multi" -not -"and not this" "w00t" hehe nice +\'test this\' -\'and this as well\'';
var regex = new RegExp('([\\+\\-]{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] + '"');
}
}

出于某种原因,只有 +test 被匹配,然后是一个空匹配,仅此而已。

最佳答案

嗯,这似乎工作正常

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] + '"');
}
}

这并不是故意的...我只是将 RegExp 重写为文字,因为我发现这样更容易阅读:)

输出

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'"

关于JavaScript Regex 只返回一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6775570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com