首页 > 解决方案 > 使用正则表达式从日期产生年份和月份

问题描述

我正在尝试使用正则表达式以 yyyy-MM 格式提取日期。

我拥有的数据可能是:

2019年9月予定 --> Should yield 201909
2020年5月 --> Should yield 202005
2019年8月下旬 --> Should yield 201908

到目前为止,我发现的唯一方法是在几个正则表达式中提取它:

(?<!年)(\d) --> Working but not nice
(?<!月)(\d) --> Not working as also selecting the year

标签: javascriptregex

解决方案


您可以执行以下操作(假设月后没有更多数字)

function extractDate(text) {
    const matches = text.match(/\d+/g);
    return matches.join(matches[1].length === 1 ? '0' : '');
}

console.log(extractDate('2019年8月下旬')) //should return 201908

console.log(extractDate('2019年12月下旬')) //should return 201912


推荐阅读