Is there a way to use anchors and lookarounds in regex together?

Viewed 55

I'm very new to using regex.

I've tried to combine an anchor and lookaround to grab the start time for day 2.

Text:

8/9/2021 8:00 AM to 6:00 PM
8/23/2021 8:00 AM to 5:00 PM

Expressions that I've tried:

\n[0-9]{1,2}\:[0-9]{2}\s[A-Z]{2}(?= to)

^[0-9]{1,2}\:[0-9]{2}\s[A-Z]{2}(?= to)

([0-9]{1,2}\:[0-9]{2}\s[A-Z]{2}){3}

In the end, I'd have a breakdown like this:

date_day1 start_day1 end_day1 date_day2 start_day2 end_day2
8/9/2021 8:00 AM 6:00 PM 8/23/2021 8:00 AM 5:00 PM

Any help would be awesome.

2 Answers

This will match the start time for day 2:

(?<=to [0-9]:[0-9]{2} [AP]M\s)[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} ([0-9]{1,2}:[0-9]{2} [AP]M)
  • the lookbehind (?<=to [0-9]:[0-9]{2} [AP]M\s) matches the end of day 1
  • [0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4} matches the date of day 2
  • ([0-9]{1,2}:[0-9]{2} [AP]M) matches start of day 2 as group

You can get it much shorter, depending on how your input might change:

(?<=M\s)[0-9\/]* ([0-9]{1,2}:[0-9]{2} [AP]M)

The issue is that you are not matching the date part 8/9/2021 before the time.

  • Using an anchor ^ can also match day 1.
  • This pattern ([0-9]{1,2}\:[0-9]{2}\s[A-Z]{2}){3} matches 3 times the time part like 5:00 PM5:00 PM5:00 PM but that is not what you want

You can match a newline \n and then the date part followed by capturing the time and match the following to

This does not make sure that the line before is also in the same format.

\n\d{1,2}/\d{1,2}/\d{4} ([0-9]{1,2}\:[0-9]{2} [A-Z]{2}) to 

Regex demo

If both lines should be of the same format (without using multiline)

^\d{1,2}/\d{1,2}/\d{4} [0-9]{1,2}:[0-9]{2} [A-Z]{2} to \d{1,2}:\d{1,2} [AP]M\n\d{1,2}/\d{1,2}/\d{4} ([0-9]{1,2}\:[0-9]{2} [A-Z]{2}) to 

Regex demo

Related