使用Regex [duplicate]匹配两个特定字符串之间的版本号

问题描述 投票:0回答:1

此问题已经在这里有了答案:

假设我有以下字符串:

这是一个非常随机的字符串,其中包含版本号3.2.1,我希望仅提取版本号。这是我不想提取的第二个版本号:5.7.8,仅用于踢球,这是第三个版本号9.0.1

是否可以仅使用一个正则表达式提取第一个版本号,即3.2.1?我正在使用JavaScript,尽管我已经能够通过使用两个单独的正则表达式来提取它,方法是搜索围绕版本号的两个字符串,然后在它们之间搜索版本号,但我还没有找到如何合并它们的方法合而为一。

非常感谢您的帮助。

谢谢

javascript regex
1个回答
1
投票

不添加/ g标志基本上只会返回第一个匹配项!如果没有匹配项,则返回null。

let string = "This is a very random string which contains the version number 3.2.1 and I’m looking to extract just the version number. This is a second version number that I don’t want to extract: 5.7.8, and just for kicks, this is a third version number 9.0.1";

firstResult = string.match(/\d.\d.\d/);

if(firstResult) {
 console.log(firstResult[0]);
}
© www.soinside.com 2019 - 2024. All rights reserved.