songs = ["Yellow Submarine";
"Penny Lane";
"Blackbird"];
colors =["Red","Yellow","Blue","Black","White"];
TF = contains(songs,colors)
TF = 3x1 logical array
1
0
1
To list the songs that contain color names, use the logical TF array as indices into the original songs
array. This technique is called logical indexing.
colorful = songs(TF)
colorful = 2x1 string
"Yellow Submarine"
"Blackbird"
Use the function replace to replace text in songs that matches elements of colors with the string
"Orange".
replace(songs,colors,"Orange")
ans = 3x1 string
"Orange Submarine"
"Penny Lane"
"Orangebird"
Match Patterns
Since R2020b
In addition to searching for literal text, like “sea” or “yellow”, you can search for text that matches a
pattern. There are many predefined patterns, such as digitsPattern to find numeric digits.
address = "123a Sesame Street, New York, NY 10128";
nums = extract(address,digitsPattern)
nums = 2x1 string
"123"
"10128"
For additional precision in searches, you can combine patterns. For example, locate words that start
with the character “S”. Use a string to specify the “S” character, and lettersPattern to find
additional letters after that character.
pat = "S" + lettersPattern;
StartWithS = extract(address,pat)
StartWithS = 2x1 string
"Sesame"
6 Characters and Strings
6-38
"Penny Lane";
"Blackbird"];
colors =["Red","Yellow","Blue","Black","White"];
TF = contains(songs,colors)
TF = 3x1 logical array
1
0
1
To list the songs that contain color names, use the logical TF array as indices into the original songs
array. This technique is called logical indexing.
colorful = songs(TF)
colorful = 2x1 string
"Yellow Submarine"
"Blackbird"
Use the function replace to replace text in songs that matches elements of colors with the string
"Orange".
replace(songs,colors,"Orange")
ans = 3x1 string
"Orange Submarine"
"Penny Lane"
"Orangebird"
Match Patterns
Since R2020b
In addition to searching for literal text, like “sea” or “yellow”, you can search for text that matches a
pattern. There are many predefined patterns, such as digitsPattern to find numeric digits.
address = "123a Sesame Street, New York, NY 10128";
nums = extract(address,digitsPattern)
nums = 2x1 string
"123"
"10128"
For additional precision in searches, you can combine patterns. For example, locate words that start
with the character “S”. Use a string to specify the “S” character, and lettersPattern to find
additional letters after that character.
pat = "S" + lettersPattern;
StartWithS = extract(address,pat)
StartWithS = 2x1 string
"Sesame"
6 Characters and Strings
6-38
