contains

Determine if pattern is in strings

Description

example

TF = contains(str,pattern) returns 1 (true) if str contains the specified pattern, and returns 0 (false) otherwise.

If pattern is an array containing multiple patterns, then contains returns 1 if it finds any element of pattern in str.

example

TF = contains(str,pattern,'IgnoreCase',true) ignores case when determining if str contains pattern.

Examples

collapse all

Create a string array that contains names. Determine which strings contain Paul.

Starting in R2017a, you can create strings using double quotes.

str = ["Mary Ann Jones","Paul Jay Burns","John Paul Smith"]
str = 1x3 string array
    "Mary Ann Jones"    "Paul Jay Burns"    "John Paul Smith"

Return a logical array where the position of each element equal to 1 corresponds to the position of a string in str that contains Paul.

pattern = "Paul";
TF = contains(str,pattern)
TF = 1x3 logical array

   0   1   1

Display the strings that contain Paul. Index back into str using TF.

str(TF)
ans = 1x2 string array
    "Paul Jay Burns"    "John Paul Smith"

Create a string array that contains names. Determine which strings contain either Ann or Paul.

Starting in R2017a, you can create strings using double quotes.

str = ["Mary Ann Jones","Christopher Matthew Burns","John Paul Smith"]
str = 1x3 string array
    "Mary Ann Jones"    "Christopher Matth..."    "John Paul Smith"

pattern = ["Ann","Paul"];
TF = contains(str,pattern)
TF = 1x3 logical array

   1   0   1

Display the strings that contain either Ann or Paul. Index back into str using TF.

str(TF)
ans = 1x2 string array
    "Mary Ann Jones"    "John Paul Smith"

Create a string array that contains names. Determine which names contain anne, ignoring case.

Starting in R2017a, you can create strings using double quotes.

str = ["Anne","Elizabeth","Marianne","Tracy"]
str = 1x4 string array
    "Anne"    "Elizabeth"    "Marianne"    "Tracy"

pattern = "anne";
TF = contains(str,pattern,'IgnoreCase',true)
TF = 1x4 logical array

   1   0   1   0

Display the strings that contain anne. Index back into str using TF.

str(TF)
ans = 1x2 string array
    "Anne"    "Marianne"

Create a character vector that contains a list of foods. Determine whether the names of different foods are in the character vector.

chr = 'peppers, onions, and mushrooms';
TF = contains(chr,'onion')
TF = logical
   1

TF = contains(chr,'pineapples')
TF = logical
   0

Input Arguments

collapse all

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

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

Extended Capabilities

Introduced in R2016b