Quantcast

Documentation Center

  • Trial Software
  • Product Updates

strmatch

Find possible matches for string

    Note:   strmatch is not recommended. Use strncmpstrncmp or validatestringvalidatestring, depending on your requirements, instead. strncmp returns the numeric index of all array elements that begin with the specified string, whereas validatestring returns a single string that represents the best match to the specified string. See Example 2, below.

    To find an exact match for a string, use strcmpstrcmp.

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 findfind 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 cellstrcellstr. Then, pass the output from cellstr to strncmp or validatestring

See Also

| | | | | | |

Was this topic helpful?