SaltyPotato
SaltyPotato

Reputation: 322

How can I extract all the 24 hour times from a string using regex?

I want to extract all the 24 hour times inside a string.

An example of a string I want to extract the times from could be:

The image has been uploaded at 20:12 and viewed at 21:04 and later was deleted around 23:43

There are 3 times I want to extract from this example string:

I've tried this pattern:

^(([1-9]{1})|([0-1][0-9])|([1-2][0-3])):([0-5][0-9])$

But it only seems to validate if a time is correct.

Upvotes: 0

Views: 56

Answers (1)

Jan
Jan

Reputation: 43169

You could use

let string = `The 30:1234 image has been uploaded at 20:12 and viewed at 21:04 and later was deleted around 23:43`;

let rx = /(\d+):(\d+)/g;

let match;

while ((match = rx.exec(string)) !== null) {
    if ((match[1] >= 0 && match[1] <= 24) && (match[2] >= 0 && match[2] <= 60)) {
        console.log(match[0]);
    }
}

Here you match any pattern digits:digits and validate them to fall in the correct ranges within JavaScript afterwards. Thus, e.g. 30:1234 will be ignored.

Upvotes: 2

Related Questions