我正在尝试操作一个字符串,该字符串经测试与我的正则表达式语句完全匹配。
我的正则表达式语句是 /\[table=\d](.*?)\[\/table]/gmi
正匹配的一个例子是 [table= 1]单元格 1[c]单元格 2[/table]
。我正在某个 div 中搜索匹配项,我将在下面的代码中将其称为 .foo
。
但是,一旦搜索返回说它找到了匹配项,我希望将被识别为匹配项的部分返回给我,以便我可以开始处理它的特定部分,即计算匹配项的数量[c]
出现的次数并引用 [table=1]
中的数字。
(function(regexCheck) {
var regex = /\[table=\d](.*?)\[\/table] / gmi;
$('.foo').each(function() {
var html = $(this).html();
var change = false;
while (regex[0].test(html)) {
change = true;
//Somehow return string?
}
});
})(jQuery);
我是 javascript 的新手,尤其是 RegEx 的新手,所以如果这段代码很粗糙,我深表歉意。
提前感谢您的所有帮助。
最佳答案
使用 exec
而不是 test
并保留生成的匹配对象:
var match;
while ((match = regex[0].exec(html)) != null) {
change = true;
// use `match[0]` for the full match, or `match[1]` and onward for capture groups
}
简单示例(由于您的代码段不可运行,我只是创建了一个简单的示例):
var str = "test 1 test 2 test 3";
var regex = /test (\d)/g;
var match;
while ((match = regex.exec(str)) !== null) {
console.log("match = " + JSON.stringify(match));
}
关于javascript - 从成功的正则表达式中获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50642624/