Home > front end >  Get all (H)H:MM timestamps from a string using RegEx
Get all (H)H:MM timestamps from a string using RegEx

Time:11-18

I am looping through strings that include two 24h timestamps without leading 0. A string looks like this

"FooBar Examplestring 4:34 - 12:30"

I understand that the regex to match a 24 hour timestamp with optional leading zero is

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

What I do not understand is, and that is some basic RegEx knowledge that I am missing here, is how I would get the two timestamps as matches from the first string.

I am using javascript btw. Here's sample code: https://jsfiddle.net/7dbfeL21/1

CodePudding user response:

Using match with the regex pattern \d{1,2}:\d{2} we can try:

var input = "FooBar Examplestring 4:34 - 12:30";
var matches = input.match(/\d{1,2}:\d{2}/g);
console.log(matches);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The pattern \d{1,2}:\d{2} is a simplification of what you were using. But given that is is unlikely that anything else in your input would match this, you might find this an easier approach.

CodePudding user response:

You have to remove the anchors ^ and $ and use word boundaries instead. You can shorted the pattern, making the first zero optional.

\b(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\b

Regex demo

let regex = /\b(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\b/g;
let str = "FooBar Samplestring 2:30 - 14:34";
var matches = str.match(regex);
console.log(matches);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related