contains

Determine if pattern is in string

Syntax

  • TF = contains(str,pattern)
    example
  • TF = contains(str,pattern,'IgnoreCase',true)
    example

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.

str = string({'Mary Ann Jones','Paul Jay Burns','John Paul Smith'})
str = 

  1×3 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 =

  1×3 logical array

   0   1   1

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

str(TF)
ans = 

  1×2 string array

    "Paul Jay Burns"    "John Paul Smith"

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

str = string({'Mary Ann Jones','Christopher Matthew Burns','John Paul Smith'})
str = 

  1×3 string array

    "Mary Ann Jones"    "Christopher Matth..."    "John Paul Smith"

pattern = {'Ann','Paul'};
TF = contains(str,pattern)
TF =

  1×3 logical array

   1   0   1

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

str(TF)
ans = 

  1×2 string array

    "Mary Ann Jones"    "John Paul Smith"

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

str = string({'Anne','Elizabeth','Marianne','Tracy'})
str = 

  1×4 string array

    "Anne"    "Elizabeth"    "Marianne"    "Tracy"

pattern = 'anne';
TF = contains(str,pattern,'IgnoreCase',true)
TF =

  1×4 logical array

   1   0   1   0

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

str(TF)
ans = 

  1×2 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

Related Examples

Input Arguments

collapse all

Input string.

Data Types: string | char | cell

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

Data Types: string | char | cell

More About

collapse all

Tall Array Support

This function fully supports tall arrays. For more information, see Tall Arrays.

Introduced in R2016b

Was this topic helpful?