Match pattern without backtracking
If a character may be matched by more than one pattern in an expression, such as digit
alphanumericsPattern + digitsPattern, all possible
combinations of matching may be tested in an attempt to find a successful match. This
process is called backtracking.
possessivePattern prevents backtracking, so once a
possessivePattern matches, the matched text is no longer able to be
matched by other parts of the pattern expression, even if that causes the pattern to fail to
possessivePattern to improve performance by limiting the
possible pattern combinations tested to find a match.
Prevent Backtracking to Match
possessivePattern so that once the possessive portion of a pattern matches, there is no backtracking. This prevents other patterns in the pattern expression to match.
txt as a string comprised of letter and digit characters. Create
nonpossessive as a pattern that matches letters or digits with
alphanumericsPattern followed by digits with
digitsPattern. On its own,
alphanumericsPattern matches the entire string, but it allows backtracking so that
digitsPattern is able to match as well.
txt = "abc123"; nonpossessive = alphanumericsPattern + digitsPattern; successfulMatch = contains(txt,nonpossessive)
successfulMatch = logical 1
alphanumericsPattern possessive. Possessiveness prevents backtracking, so
alphanumericsPattern matches the entire string and does not backtrack to allow
digitsPattern to match as well. This attribute causes
possessive to fail to match
possessive = possessivePattern(alphanumericsPattern) + digitsPattern; unsuccessfulMatch = contains(txt,possessive)
unsuccessfulMatch = logical 0
Introduced in R2020b