提问者:小点点

从动态字符串中提取数字[重复]


字符串是动态的。示例

Date18:Month5:Year1984

我们怎么能只提取18号。 我不能使用substring,因为值是动态的。我只想提取日期之后和日期之前的数字:


共2个答案

匿名用户

以下是您想要的:

null

const a = "Date18:Month5:Year1984";
const match = a.match(/^Date([0-9]+?):/);

if(match){
  console.log(match[1]);
}

匿名用户

正则表达式非常适合匹配模式。 你可以用很多方法来写它,这里有几种方法。

null

var str = "Date18:Month5:Year1984"

const re = /^Date(\d+):Month(\d+):Year(\d+)$/;

const match = str.match(re);

console.log(match[1], match[2], match[3]);


const re2 = /(\d+)/g;

const match2 = str.match(re2);

console.log(match2[0], match2[1], match2[2]);