gpt4 book ai didi

javascript - 用于时间跟踪的正则表达式验证

转载 作者:行者123 更新时间:2023-12-05 01:52:00 24 4
gpt4 key购买 nike

我正在尝试以 Javascript 在 Jira 中完成的方式验证字符串。我正在尝试复制它在 Jira 中的验证方式。我猜我可以用 Regex 做到这一点,但我不确定怎么做。

用户可以输入格式为“1d 6h 30m”的字符串,表示 1 天 6 小时 30 分钟。我的用例不需要几周的时间。如果用户使用无效字符(除“d”、“h”、“m”或“”之外的任何字符),我想显示错误。此外,字符串必须用空格分隔持续时间,理想情况下,我想强制用户按降序输入持续时间,这意味着“6h 1d”将无效,因为天数应该排在第一位。此外,用户不必输入所有信息,因此“30m”是有效的。

这是我的代码,用于获取似乎有效的日期、小时和分钟。我只需要验证部分的帮助。

let time = '12h 21d 30m'; //example
let times = time.split(' ');
let days = 0;
let hours = 0;
let min = 0;
for(let i = 0; i < times.length; i++) {
if (times[i].includes('d')){
days = times[i].split('d')[0];
}
if (times[i].includes('h')){
hours = times[i].split('h')[0];
}
if (times[i].includes('m')){
min = times[i].split('m')[0];
}
}
console.log(days);
console.log(hours);
console.log(min);

enter image description here

最佳答案

const INPUT = "12h 21d  30s";

checkTimespanFormat(INPUT);

if (checkTimespanKeysOrder(INPUT, true))
console.log(`${INPUT} keys order is valid`);
else console.log(`${INPUT} keys order is NOT valid`);
//******************************************************************

/**
* Ensures that time keys are:
* - Preceeded by one or two digits
* - Separated by one or many spaces
*/
function checkTimespanFormat(timespanStr, maltiSpacesSeparation = false) {
// timespan items must be separated by 1 space
if (maltiSpacesSeparation) timespanStr = timespanStr.toLowerCase().split(" ");
// timespan items must be separated by one or many space
else timespanStr = timespanStr.toLowerCase().split(/ +/);

// timespan items must be formatted correctly
timespanStr.forEach((item) => {
if (!/^\d{1,2}[dhms]$/.test(item)) console.log("invalid", item);
else console.log("valid", item);
});
}

/**
* Validates:
* - Keys order
* - Duplicate keys
*/
function checkTimespanKeysOrder(timespanStr) {
const ORDER = ["d", "h", "m", "s"];

let timeKeysOrder = timespanStr
.replace(/[^dhms]/g, "") // Removing non time keys characters
.split("") // toArray
.map((char) => {
return ORDER.indexOf(char); // Getting the order of time keys
});

for (i = 0; i < timeKeysOrder.length - 1; i++)
if (timeKeysOrder.at(i) >= timeKeysOrder.at(i + 1)) return false;
return true;
}

关于javascript - 用于时间跟踪的正则表达式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71874347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com