Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

Searching and Replacing

MATLAB® provides several functions for searching and replacing characters in a character array. (MATLAB also supports search and replace operations using regular expressions. See Regular Expressions.)

Consider a character vector named label:

label = 'Sample 1, 10/28/95';

The strrep function performs the standard search-and-replace operation. Use strrep to change the date from '10/28' to '10/30':

newlabel = strrep(label, '28', '30')
newlabel =
   Sample 1, 10/30/95

strfind returns the starting position of a term you specify within a longer character vector. To find all occurrences of 'amp' inside label, use

position = strfind(label, 'amp')
position =
    2

The position within label where the only occurrence of 'amp' begins is the second character.

The textscan function parses a character array to identify numbers or subarrays of characters. Describe each component with conversion specifiers, such as %s for character vectors, %d for integers, or %f for floating-point numbers. Optionally, include any literal text to ignore.

For example, identify the sample number and date from label:

parts = textscan(label, 'Sample %d, %s');
parts{:}

ans =
           1
ans = 
    '10/28/95'

To parse character vectors in a cell array, use the strtok function. For example:

c = {'all in good time'; ...
     'my dog has fleas'; ...
     'leave no stone unturned'};
first_words = strtok(c)
Was this topic helpful?