Main Content


Make pattern optional to match

Since R2020b



newpat = optionalPattern(pat) creates a pattern that matches pat when possible, but matching pat is not required for a pattern expression to match successfully. Use this function in conjunction with other pattern functions to build patterns that are more flexible in their matching requirements.


collapse all

Use optionalPattern to designate a pattern as optional to match.

Create txt as a string. Create a pattern, pat, that matches "foo" and will optionally match "bar" so long as it is preceded by "foo". Extract the pattern.

txt = "foo bar foobar";
pat = "foo" + optionalPattern("bar");
ans = 2x1 string

Build a pattern that matches combinations of letters and periods after an "@". Use optionPattern to match subdomains if present. If a subdomain is not present, optionalPattern does not prevent a match if other conditions of pat are met. Extract the pattern.

emails = [""
pat = lookBehindBoundary("@") + optionalPattern(lettersPattern + ".") + lettersPattern + "." + lettersPattern;
domains = extract(emails,pat)
domains = 3x1 string

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.

Extended Capabilities

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced in R2020b