Main Content

optionalPattern

Make pattern optional to match

Since R2020b

Description

example

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.

Examples

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");
extract(txt,pat)
ans = 2x1 string
    "foo"
    "foobar"

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 = ["Sue_B@nonprofit.org"
          "JohnDRoc12@business.com"
          "R.Franklin@biology.university.org"];
pat = lookBehindBoundary("@") + optionalPattern(lettersPattern + ".") + lettersPattern + "." + lettersPattern;
domains = extract(emails,pat)
domains = 3x1 string
    "nonprofit.org"
    "business.com"
    "biology.university.org"

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