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

如何用JavaScript正则提取CDN文本中latestVersion的版本号

提取CDN返回文本中latestVersion的版本号

我是正则表达式新手,现有一个返回文本内容的CDN URL,希望使用JavaScript匹配并提取其中latestVersion对应的版本号。我能匹配到latestVersion,但不知道如何获取它内部的值。

示例文本:

...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...

我尝试了以下代码,但未能成功匹配到目标内容:

const regex = /\blatestVersion:"*"\b/;
stringIneed = text.match(regex);

我只需要版本号(如1.3.0),不需要包含latestVersion:前缀。


解决方案

你的正则写法有两个问题:一是"*是匹配0个或多个引号实体,根本没法定位到引号里的版本号;二是没设置捕获组,就算匹配到整段内容也拿不到单独的版本号。

直接用带捕获组的正则就能解决,看下面的代码:

const text = '...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...';
// 正则里用括号把版本号部分包起来,作为捕获组
const regex = /latestVersion:"([\d.]+)"/;
const match = text.match(regex);
// 匹配成功的话,捕获组的结果在match[1]里
const latestVersion = match ? match[1] : '未找到版本号';
console.log(latestVersion); // 输出:1.3.0

正则拆解

  • latestVersion:":精准匹配前缀,定位到目标字段
  • ([\d.]+):捕获组,[\d.]匹配数字或点,+表示至少出现一次,刚好覆盖版本号的格式
  • ":匹配字段结尾的引号实体

如果你的文本里可能有多个latestVersion条目,用全局匹配模式加上循环就能把所有版本号捞出来:

const regex = /latestVersion:"([\d.]+)"/g;
let currentMatch;
const allVersions = [];
while ((currentMatch = regex.exec(text)) !== null) {
  allVersions.push(currentMatch[1]);
}
console.log(allVersions); // 输出所有匹配到的版本号数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:01:05