Search and Replace Text
Since R2016b. Replaces Searching and Replacing (R2016a).
Processing text data often involves finding and replacing substrings. There are several functions that
find text and return different information: some functions confirm that the text exists, while others
count occurrences, find starting indices, or extract substrings. These functions work on character
vectors and string scalars, such as "yes", as well as character and string arrays, such as
["yes","no";"abc","xyz"]. In addition, you can use patterns to define rules for searching, such as
one or more letter or digit characters.
Search for Text
To determine if text is present, use a function that returns logical values, like contains,
startsWith, or endsWith. Logical values of 1 correspond to true, and 0 corresponds to false.
txt = "she sells seashells by the seashore";
TF = contains(txt,"sea")
TF = logical
1
Calculate how many times the text occurs using the count function.
n = count(txt,"sea")
n = 2
To locate where the text occurs, use the strfind function, which returns starting indices.
idx = strfind(txt,"sea")
idx = 1×2
11
28
Find and extract text using extraction functions, such as extract, extractBetween,
extractBefore, or extractAfter.
mid = extractBetween(txt,"sea","shore")
mid =
"shells by the sea"
Optionally, include the boundary text.
mid = extractBetween(txt,"sea","shore","Boundaries","inclusive")
mid =
"seashells by the seashore"
Find Text in Arrays
The search and replacement functions can also find text in multi-element arrays. For example, look
for color names in several song titles.
Search and Replace Text
6-37
Précédent

- 219/1450

Suivant