Bhumi Patel
Bhumi Patel

Reputation: 35

Regular Expression for 3:00pm to 4:20

I need regular expression for find particular pattern like .

String : In meeting 3:00pm to 4:20 at Ahmedabad.

From that String i need only 3:00pm to 4:20.

and expression :

var time_range = message.match**(/(\w+)\s(to)\s(\w+)/gi)**

but this expression have some limitations.

  1. In meeting 3pm to 6pm at Ahmedabad (its work fine) but
  2. In meeting 3:40pm to 6:30pm at Ahmedabad(than there is problem because of (:))

Upvotes: 0

Views: 79

Answers (2)

vks
vks

Reputation: 67978

\d+(?::\d+)?\s*(?:[ap]m)?\s*to\s*\d+(?::\d+)?\s*(?:[ap]m)?

Try this.See demo.

https://regex101.com/r/vD5iH9/49

var re = /\d+(?::\d+)?\s*(?:[ap]m)?\s*to\s*\d+(?::\d+)?\s*(?:[ap]m)?/gm;
var str = 'In meeting 3:00pm to 4:20 at Ahmedabad.\nIn meeting 3pm to 6pm at Ahmedabad\nIn meeting 3:00pm to 4:20am at Ahmedabad.';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174756

This regex would work for most cases and it won't check for the proper time.

\b(\d{1,2}(?::\d{1,2})?(?:[ap]m))\s(to)\s(\d{1,2}(?::\d{1,2})?(?:[ap]m))\b

DEMO

For simple case, just put : and \w inside a character class and makes it to repeat one or more times by adding + quantifier next to that character class.

([:\w]+)\s(to)\s([:\w]+)

DEMO

Upvotes: 2

Related Questions