JavaScript Regex 仅返回一个匹配项

标签 javascript regex

我看不出我错在哪里:

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/

相关文章:

javascript - 在事件处理程序内部进行 setState 调用后,React 何时重新呈现

javascript - 如何将 JSON 对象结构转换为点表示法?

javascript - 检查模拟时钟的指针位置是否正确

javascript - 增量 CSS3 淡入

javascript - Bootstrap 嵌套导航选项卡不会在重新加载时打开相同的选项卡

JavaScript 正则表达式删除完美匹配的任何前缀

java - 将字符串输入文本与 MySQL 和 Java 中的现有字符串匹配

正则表达式捕获 : word {word} word

javascript - 使用 RegExp 和 exec 在 JavaScript 中解析 XML - 它通常可以工作,但在少数情况下却不能 - 知道为什么吗?

javascript - 替换另外 2 个符号之间的所有符号