我有兩種 dateString 格式,比如:date-f1: 2and :date-f2:-1,如果傳入的字串是date-f1: 2格式的,我需要 console.log 為 processesDate.format("YYYY-MM-DD"),但如果傳入的字串是:date-f2:-1格式,我需要控制臺。記錄為 processesDate.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);
uj5u.com熱心網友回復:
我修改了你的正則運算式并添加了命名捕獲組,試試這個:/^: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))
所以你不必創建額外的 varsword和operator.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460137.html
標籤:javascript 正则表达式
