Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fails to match when using backreference

I want to match

9:00 AM to 5:00 PM

This is my regex, I am trying to use backreference match the time at the end, it is not working

(\d(?::\d{2})?\s\wM)\sto\s\1

If simply replacing the backreference makes it match, why is the backreference failing ?
(\d(?::\d{2})?\s\wM)\sto\s(\d(?::\d{2})?\s\wM)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My questions are,
How can I use a backreference to match the time at both ends ?

Why is what I did not working ?

regexr.com/7dbki

>Solution :

I think there is a misconception of what \1 does. It does not re-use the pattern, as if it was a placeholder for the expression you put in parenthesis. Rather, it matches whatever was captured in the first capturing group.

In your case, your pattern would match e.g. this:

  • 9:00 AM to 9:00 AM

See here: https://regex101.com/r/M8u6eO/1

If your regex engine supports it, you may use "?1".

(\d:\d{2}?\s\wM)\sto\s(?1)

See here: https://regex101.com/r/OytMlt/1

This will indeed re-use the pattern instead of the match.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading