regex 引号内的正则表达式特定数字

uqjltbpv  于 2022-12-14  发布在  其他
关注(0)|答案(3)|浏览(123)

我是regex的新手,有一个返回text的cdn url,我想用javascript来匹配和提取版本号。我可以匹配latestVersion,但我不知道如何得到它里面的值。
text上的交货日期:

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

我尝试执行此行以显示latestVersion:"1.3.0,但不成功

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

我只需要1.3.0,不包括字符串latestVersion:

kzipqqlq

kzipqqlq1#

您可以使用lookbehind或撷取群组,如下所示:

const str = '...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...'

console.log(
  str.match(/(?<=latestVersion:")[^"]+/)?.[0]
)

console.log(
  str.match(/latestVersion:"([^"]+)"/)?.[1]
)
v2g6jxz6

v2g6jxz62#

尝试添加捕获组()以匹配Regex中的某些字符串。

/\blatestVersion:"([0-9.]+)"/
olqngx59

olqngx593#

有很多方法可以做到这一点。这是一个:

const text='...oldVersion:"1.2.0",stagingVersion:"1.2.1",latestVersion:"1.3.0",authVersion:"2.2.2"...';

console.log(text.match(/latestVersion:"(.*?)"/)?.[1])

.*?是一个“非贪婪”通配符,它将匹配尽可能少的字符,以便匹配整个正则表达式。因此,它将在"之前停止匹配。

相关问题