使用正则表达式如何执行字符串匹配以获得不同的日期格式

Using regex how to perform string match to get a different date format

我有两种dateString格式,比如:date-f1:+2:date-f2:-1,如果传入的字符串是date-f1:+2格式,我需要console.log as processedDate.format ("YYYY-MM-DD"),但是如果传入的字符串是:date-f2:-1格式,我需要console.log as processedDate.format("DD/MM/YYYY")。我试过下面的方法,但出现异常 Cannot read properties of null (reading '1')",有人可以指教吗;

let dateString = ":date-f1:+2";  // or ":date-f2:-1"

    function datesParse(dateString) {
        
    let matchFormat = dateString.match(/^:date-f1:(|):date-f2:(?:([\-\+])([0-9]+)+)?$/);

        let processedDate = moment();
        if (matchFormat[1] === "-") {
            processedDate = processedDate.subtract(matchFormat[2], 'days');
            console.log("Date::"+processedDate.format("DD/MM/YYYY"));
        } else if (matchFormat[1] === "+") {
            processedDate = processedDate.add(matchFormat[2], 'days');
            console.log("Date::"+processedDate.format("DD/MM/YYYY"));
        } else if (matchFormat[1] === "-") {
            processedDate = processedDate.subtract(matchFormat[2], 'days');
            console.log("Date::"+processedDate.format("YYYY-MM-DD"));
        } else if (matchFormat[1] === "+") {
            processedDate = processedDate.add(matchFormat[2], 'days');
            console.log("Date::"+processedDate.format("YYYY-MM-DD"));
        }
        
    }
    
    datesParse(dateString);

我修改了你的正则表达式并添加了命名捕获组,试试这个:/^:date-(?<word>f[12]):(?:(?<operator>[-+])(?<number>[0-9]+)+)?$/gm

在这里测试:https://regex101.com/r/cNNHA5/1

使用捕获组,您可以轻松访问每个捕获的元素:

let line = ':date-f1:+2';

let pattern = /^:date-(?<word>f[12]):(?:(?<operator>[-+])(?<number>[0-9]+)+)?$/gm

let match = pattern.exec(line)

console.log('word', match.groups.word)
console.log('operator', match.groups.operator)
console.log('number', match.groups.number)

并使用它们进行检查,例如:

if (dateString.includes(match.groups.word) && dateString.includes(match.groups.operator))

因此您不必创建额外的变量 wordoperator