0

I am trying to find a solution to extract the time given in a dynamic string using regex object using JavaScript.

For example - Assume the string to be "Please provide access to the engineer: last name: XYZ first name: ABC date: 02nd November 2021 time window: 11:00AM - 07:00PM CET". I need to extract the time i.e 11:00AM - 07:00PM CET from this.

I tried using the regex expression for time -

/^(0?[1-9]|1[0-2]):([0-5]\d)\s?((?:A|P)\.?M\.?)$/i

and few more other expressions. However whenever I test the returned value is false.

What is the approach to solve this ?

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    You can remove the anchors `^` and `$` to match the times as they are not the only thing in the string https://regex101.com/r/yQQlUK/1 You can shorten the group for `(?:A|P)` to `[AP]` – The fourth bird Nov 15 '21 at 17:51
  • Of course, remove the anchors. The `^` may be replace with `\b` or `(?<!\d)` if you need to use some boundary. – Wiktor Stribiżew Nov 15 '21 at 17:51
  • 1
    You could do something like this: https://regex101.com/r/CIDS3R/1 – Steve Nov 15 '21 at 17:55
  • 4
    @WiktorStribiżew Did you even read the question before closing this? That link has nothing to do with the OP question. ‍♂️ – Steve Nov 15 '21 at 17:58

0 Answers0