假设我有一个像这样的网址:
url = http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236
如何使用正则表达式仅提取“pid=”之后的值,而不使用正则表达式提取文本本身。
这是我的正则表达式现在的样子:
url.match(/pid=(\w+)/g)
给出以下输出:
["pid=1234", "pid=1235", "pid=1236"]
但我想得到这样的:
["1234", "1235", "1236"]
如果我在这里做错了什么,请纠正我。
最佳答案
简单的解决方案是:
url.match(/(?<=pid=)(\d+)/g);
但是,由于 Javascript 不支持lookbehind,因此您需要循环遍历结果:
var results = [];
url.match(/pid=(\d+)/g).forEach(function(result) {
results.push(result.replace('pid=', ''));
});
console.log(results); // ["1234", "1235", "1236"]
关于javascript - 如何在 JavaScript 中使用带有 'g' 选项的正则表达式仅提取分组文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970730/