Skip to Main Content Skip to Search
Product Documentation

strmatch - Find possible matches for string

Syntax

x = strmatch(str, strarray)
x = strmatch(str, strarray, 'exact')

Description

x = strmatch(str, strarray) looks through the rows of the character array or cell array of strings strarray to find strings that begin with the text contained in str, and returns the matching row indices. If strmatch does not find str in strarray, x is an empty matrix ([]). Any trailing space characters in str or strarray are ignored when matching. strmatch is fastest when strarray is a character array.

x = strmatch(str, strarray, 'exact') compares str with each row of strarray, looking for an exact match of the entire strings. Any trailing space characters in str or strarray are ignored when matching.

Examples

Example 1

The statement

x = strmatch('max', char('max', 'minimax', 'maximum'))

returns x = [1; 3] since rows 1 and 3 begin with 'max'. The statement

x = strmatch('max', char('max', 'minimax', 'maximum'),'exact')

returns x = 1, since only row 1 matches 'max' exactly.

Example 2

This example shows how to replace use of the strmatch function with validatestring or strncmp.

To start with, use strmatch to return the index of those elements for which there is a match:

list = {'max', 'minimax', 'maximum', 'max'}
x = strmatch('max',list)
x =
     1
     3
     4

validatestring returns the string representing the best match. If multiple or no matches exist, this statement would return an error:

list = {'max', 'minimax', 'maximum', 'max'};
x = validatestring('max', list)
x =
   max

strncmp returns a logical array indicating which strings match the specified string:

list = {'max', 'minimax', 'maximum', 'max'};
x = strncmp('max', list, 3)
x =
     1     0     1     1

If you prefer that MATLAB return the numeric indices of list, use find as follows:

list = {'max', 'minimax', 'maximum', 'max'}
x = find(strncmp(list, 'max', 3))

If your input to strmatch is a character matrix, then first convert the matrix to a cell array using cellstr. Then, pass the output from cellstr to strncmp or validatestring

See Also

regexp | regexpi | regexprep | strcmp | strcmpi | strfind | strncmp | strncmpi

  


» Learn more
» Download free kit
» Get trial software

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS