regexbackreference

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)

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:

    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.