Main Content


Match pattern without backtracking



newpat = possessivePattern(pat) creates a pattern that does not backtrack within pat once pat matches.

If a character may be matched by more than one pattern in an expression, such as digit characters with 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 match. Use possessivePattern to improve performance by limiting the possible pattern combinations tested to find a match.


collapse all

Use 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.

Create 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

Make 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 txt.

possessive = possessivePattern(alphanumericsPattern) + digitsPattern;
unsuccessfulMatch = contains(txt,possessive)
unsuccessfulMatch = logical

Input Arguments

collapse all

Input pattern, specified as a pattern, string array, character vector, or cell array of character vectors.

Data Types: char | string | pattern | cell

Output Arguments

collapse all

Output pattern, returned as a pattern or an array of pattern objects.

Introduced in R2020b