user3062521
user3062521

Reputation: 21

Find the match extract next n chars but exclude a match itself

I am not a regex savvy so my question may seem simple. How do you extract hours and minutes from a string like this:

2013-12-03T10:45:33-07:00

So I just want to get 10:45 from the above string and ignore the rest.

I tried /[0-2][0-9]:[0-5][0-9]/ but that gives me: 10:45 as well as 07:00

Also tried /[T][0-2][0-9]:[0-5][0-9]/ , but this gives me T10:45

I tried excluding 'T' by using a ^ anchor [^T][ ][ ]:[ ][ ] but this gave me -07:00 !

I thought about searching for the first occurrence of ':' but I don't know how to extract 2 digits before and after ':' and include the ':' itself.

Any help with a comment would be greatly appreciated.

Upvotes: 2

Views: 66

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39522

You can use a positive lookbehind for this:

/(?<=T)\d{2}:\d{2}/

What this essentially means it that we're matching two digits followed by a colon followed by 2 digits, but they MUST have a "T" in front. Do not, however, add this to the match as lookaheads/behinds are not matched.

DEMO

[^T] means "any character that isn't T", which is why it didn't work.


JS regex does not support lookaheads/behinds (see?), but you can simply create a matching group using /T(\d{2}:\d{2})/ and then match [1]:

var timeString = '2013-12-03T10:45:33-07:00';
var time = timeString.match(/T(\d{2}:\d{2})/)[1];
console.log(time); //10:45

Upvotes: 2

Uri Mikhli
Uri Mikhli

Reputation: 675

A simple way to extract without heavy regex knowledge would be to do something like

foo = "2013-12-03T10:45:33-07:00"
(hours,minutes,junk) = foo.split ":"
hours =~ s/*(\d\d)$/$1/

so now you have

hours and minutes available for use

Upvotes: 1

Related Questions