tags:

views:

159

answers:

5

Can someone provide me with a regex for the following? (Using Javascript)

source string: Jan 2 2010 6:00PM

I want the resulting string to show only the time, as shown below. (example above used)

result string: 6:00 PM

+6  A: 

Replace (\d{1,2}:\d{1,2})([AP]M) with \1 \2

Update: Use \d{2} instead of \d{1,2} if the source string is guaranteed to be in the HH:MM format.

Amarghosh
+1, but `:\d{1,2}` should be `:\d{2}`, as seconds always uses 2 digits
Rubens Farias
Ya, I was just being lenient - hour part in OP's example was single digit.
Amarghosh
Rubens: I see no seconds, but minutes! :P
Roger Pate
99:77PM will be okay by this pattern. SimpleDateFormat is best.
fastcodejava
This is for extracting time from a given date-time string - not for validating time in any given string.
Amarghosh
Amarghosh: HH:MM isn't guaranteed, the example doesn't even follow that.
Roger Pate
A: 

You could use SimpleDateFormat with the format MMM dd yyyy HH:mm. Then you can get the time part.

fastcodejava
A: 

While I haven't looked I'm sure you'll be able to find something that will work for you at the Regex Library website. However I happen to agree with SilentGhost in that it might be easier to just split the string. Just make sure all DateTimes are are in the same format.

Zerodestiny
+1  A: 

Implementing SilentGhost's comment in regex: /([^ ]+)([^ ]{2})$/

This will match the last space-delimited "word", with the first bit in group 1 and the last two chars in group 2. The translation to string operations instead should be straight-forward.

You could also replace the (..) with [AP]M or similar, if desired, and might benefit from a tiny bit of validation if you construct the regex to prevent something like blah blah haha-I-gave-garbage-inputPM, but there are many ways to deal with garbage anyway.

Roger Pate
A: 

If you need to convert it into a date object, and if you're using Javascript in a web browser, you might want this instead:

new Date('Jan 2 2010 6:00PM'.replace(/(?=[AP]M)/i, ' '));
// Sat Jan 02 2010 18:00:00 GMT-0600 (Central Standard Time)

new Date('Jan 2 2010 6:00PM'.replace(/(?=[AP]M)/i, ' ')).toUTCString();
// Sun, 03 Jan 2010 00:00:00 GMT

Mozilla has reference documentation on the Javascript Date object.

Anonymous