Backtracking of quantified subpatterns

Q

What is backtracking of quantified subpatterns? What does it mean that a quantified subpattern is "backtracked"?

How to show that a quantified subpattern is "backtracked" on this PHP script: if ($t=10): echo "Just started...!"; endif; if ($t=11): echo "Hungry!"; endif; if ($t=12): echo ""Ah, lunch-time!"; endif;?

✍: FYIcenter.com

A

The backtracking behavior of quantified subpatterns is referring to the default behavior of backtracking repeated matches of a quantified subpattern to allow the rest of the pattern to match.

This default backtracking behavior is very useful in many cases. For example, the pattern /\w+day/ will have no match on "Sunday" without backtracking, because the quantified subpattern '\w+' is "greedy" by default. It will not stop after mathching "Sun" and continue to match the entire string of "Sunday". The next subpattern is 'd' and causing the entire matching process to fail, since there is nothing left to match against.

With the default backtracing behavoir, /\w+day/ will match on "Sunday", because '\w+' will first match to "Sunday", then backtrack 3 times to return 3 characters to match the rest of the pattern 'day'. In other words,

(\w+)day   # matches 'Sunday' with $1='Sun', backtracked from 'Sunday'

The regular expression to show a quantified subpattern is "backtracked" on the given PHP script:

(if .+ endif;)

if - matches 'if'
.+ endif; - '.+' matches all characters to the end, 
            backtracked 8 characters to match ' endif'

Click the button to test this regular expression here online:

2013-01-26, 0👍, 0💬