从分钟和小时或几天和小时的字符串中计算分钟

时间:2018-10-20 20:18:22

标签: javascript regex

我有一个函数,它需要花费数小时和数分钟或数天和数小时的字符串,并将其转换为分钟。

calculate(s) {
    const matches = /(?:(\d+) hours?)? ?(?:(\d+) mins?)?/.exec(s);
    return Number(matches[1] || 0) * 60 + Number(matches[2] || 0);
};

如果输入如下,我可以设法找到分钟数:

console.log(calculate('1 hour 5 mins')); // 65
console.log(calculate('2 hours 1 min')); // 121
console.log(calculate('3 hours')); // 180
console.log(calculate('10 mins')); // 10

但是,如果输入为以下内容,我如何找到分钟数:

console.log(calculate('1 day 5 hours'));
console.log(calculate('2 days 15 hours'));
console.log(calculate('3 days 16 hours 32 mins'));

2 个答案:

答案 0 :(得分:1)

只需使用相同的逻辑在 hours 部分的前面添加 days 部分:

(?:(\d+) days? ?)?(?:(\d+) hours? ?)?(?:(\d+) mins?)?

在代码中,这将是:

    function calculateMinutes(s) {
        const matches = /(?:(\d+) days? ?)?(?:(\d+) hours? ?)?(?:(\d+) mins?)?/.exec(s);
        return   Number(matches[1] || 0) * 24*60
               + Number(matches[2] || 0) * 60
               + Number(matches[3] || 0);
    };
    console.log(calculateMinutes('1 hour 5 mins')); // 65
    console.log(calculateMinutes('2 hours 1 min')); // 121
    console.log(calculateMinutes('3 hours')); // 180
    console.log(calculateMinutes('10 mins')); // 10
    console.log(calculateMinutes('1 day 5 hours')); // 1740
    console.log(calculateMinutes('2 days 15 hours')); // 3780
    console.log(calculateMinutes('3 days 16 hours 32 mins')); // 5312
    console.log(calculateMinutes('2 hours')); // 120
    console.log(calculateMinutes('1 day')); // 1440
    console.log(calculateMinutes('1 day 16 hours')); 

Regex fiddle

答案 1 :(得分:1)

以下解决方案适用于所有示例。如果您跳过某些单位,例如K(无小时),或使这些单元乱序,例如1 day 3 mins

5 mins 10 hours