-3

Need some help with regex for extracting time from the following string:

3:00 am - 4:00 pm Transform data blah blah blah

or

3:00 am Transform data blah blah blah

Following regex works for the first format but it does not work for the second format: /\d{1,2}:\d\d\s([AaPp][Mm])?\s?-?\s\d{1,2}:\d\d\s([AaPp][Mm])/g

Lorenz Meyer
  • 17,418
  • 21
  • 68
  • 109
Indu527
  • 19
  • 4
  • 2
    [*Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.* - Jamie Zawinski](http://regex.info/blog/2006-09-15/247) –  Jun 15 '17 at 18:16
  • 1
    Please read [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions. –  Jun 15 '17 at 18:17
  • Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions. –  Jun 15 '17 at 18:18
  • this is what you want:-https://eval.in/817294? – Serving Quarantine period Jun 15 '17 at 18:25
  • Enclose second section in an optional cluster `\d{1,2}:\d\d\s([AaPp][Mm])?\s?(-?\s\d{1,2}:\d\d\s([AaPp][Mm]))?` – revo Jun 15 '17 at 18:25
  • Possible duplicate of [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – revo Jun 15 '17 at 18:26
  • Maybe this approach would interest you: https://stackoverflow.com/a/141504/1575353 – Sᴀᴍ Onᴇᴌᴀ Jun 15 '17 at 18:28
  • Hey Revo, it only filters start date but not end date – Indu527 Jun 15 '17 at 18:35

1 Answers1

-1

The modifier g allows finding all occurrences. Thus you can simplify your expression. Also the modifier i allows case insensitive matching.

/\d{1,2}:\d{2}\s(am|pm)/gi

This is how to use :

var str = '3:00 am - 4:00 pm Transform data blah blah blah', 
times = str.match(/\d{1,2}:\d{2}\s(am|pm)/gi);
console.log(times);

times will be an array that contains the matches.

Lorenz Meyer
  • 17,418
  • 21
  • 68
  • 109