%% Match Email Addresses
% Build an easy to read pattern to match email addresses.
% Email addresses follow the structure userename@domain.TLD, where userename and domain are made up of identifiers separated by periods. Build a pattern that matches identifiers composed of any combination of alphanumeric characters and "_" characters. Use maskedPattern to name this pattern identifier.

identifier = asManyOfPattern(alphanumericsPattern(1) | "_", 1);
identifier = maskedPattern(identifier);

% Build patterns to match domains and subdomains comprised of identifiers. Create a pattern that matches TLDs from a specified list.

subdomain = asManyOfPattern(identifier + ".") + identifier;
domainName = namedPattern(identifier,"domainName");
tld = "com" | "org" | "gov" | "net" | "edu";

% Build a pattern for matching the local part of an email, which matches one or more identifiers separated by periods. Build a pattern for matching the domain, TLD, and any potential subdomains by combining the previously defined patterns. Use namedPattern to assign each of these patterns to a named pattern.

username = asManyOfPattern(identifier + ".") + identifier;
domain = optionalPattern(namedPattern(subdomain) + ".") + ...
            domainName + "." + ...
            namedPattern(tld);

% Combine all of the patterns into a single pattern expression. Use namedPattern to assign username, domain, and emailPattern to named patterns.

emailAddress = namedPattern(username) + "@" + namedPattern(domain);
emailPattern = namedPattern(emailAddress)

% Create a string that contains an email address, and then extract the pattern from the text.

txt = "You can reach me by email at John.Smith@department.organization.org";
extract(txt,emailPattern)

% Named patterns allow dot-indexing in order to access named subpatterns. Use dot-indexing to assign a specific value to the named pattern domain.

emailPattern.emailAddress.domain = "mathworks.com"

% Copyright 2020 The MathWorks, Inc.