You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript正则匹配:如何仅返回匹配结果的指定部分?

仅用正则提取目标数字的解决方案

当然可以只用正则直接提取你要的数字,不需要额外调用replace,给你几种可行的方法:

方法1:使用正向肯定断言

用正向断言匹配后面跟着calorie的数字,断言部分不会被包含在匹配结果里:

const t = "The 2 items contained 150 calories";
const targetNum = t.match(/\d+(?= calorie)/g);
console.log(targetNum); // 输出 ["150"]

这里(?= calorie)是正向肯定断言,作用是确保前面的数字后面紧跟 calorie,但不会把这段后缀加入匹配结果。

方法2:利用捕获组提取

如果需要更灵活的处理(比如匹配多个结果),可以用捕获组,通过exec或matchAll直接获取分组内容:

单次匹配用exec

const t = "The 2 items contained 150 calories";
const regex = /(\d+) calorie/g;
const matchResult = regex.exec(t);
if (matchResult) {
  console.log(matchResult[1]); // 输出 "150"
}

matchResult[1]就是正则里括号(\d+)捕获到的数字部分。

多次匹配用matchAll

如果字符串里有多个符合条件的数字,用matchAll遍历所有匹配项:

const t = "The 2 items contained 150 calorie and 200 calorie";
const regex = /(\d+) calorie/g;
const allMatches = [...t.matchAll(regex)];
const nums = allMatches.map(item => item[1]);
console.log(nums); // 输出 ["150", "200"]

你原有代码的问题

你原来的match(/(\d+) calorie/g)返回的是包含完整匹配项的数组(比如["150 calorie"]),直接调用replace其实是对数组转字符串后操作,所以结果不符合预期。而上面的正则方法可以直接拿到目标数字。

内容的提问来源于stack exchange,提问作者Richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:55:16