Documentation

This is machine translation

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

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

replace

Find and replace substrings in string array

Syntax

newStr = replace(str,old,new)

Description

example

newStr = replace(str,old,new) replaces all occurrences of old in string array str with new. If old contains multiple substrings, then new either must be the same size as old, or must be a single substring.

Examples

collapse all

Replace placeholder text in a list of file names.

Starting in R2017a, you can create strings using double quotes instead of the string function.

str = ["<ROOT_DIR>\MyData\data.tar.gz";
       "<ROOT_DIR>\MyScripts\cleandata.m";
       "<ROOT_DIR>\MyScripts\preprocess.m";
       "<ROOT_DIR>\MyScripts\publishResults.m"]
str = 4×1 string array
    "<ROOT_DIR>\MyData\data.tar.gz"
    "<ROOT_DIR>\MyScripts\cleandata.m"
    "<ROOT_DIR>\MyScripts\preprocess.m"
    "<ROOT_DIR>\MyScripts\publishResults.m"

Replace <ROOT_DIR> with a string that is the name of a file path.

old = "<ROOT_DIR>";
new = "C:\MyProject";
newStr = replace(str,old,new)
newStr = 4×1 string array
    "C:\MyProject\MyData\data.tar.gz"
    "C:\MyProject\MyScripts\cleandata.m"
    "C:\MyProject\MyScripts\preprocess.m"
    "C:\MyProject\MyScripts\publishResults.m"

Replace carriage returns with newline characters.

Starting in R2017a, you can create strings using double quotes instead of the string function.

str = ["Submission Date: 11/29/15\r";
       "Acceptance Date: 1/20/16\r";
       "Contact: john.smith@example.com\r\n"]
str = 3×1 string array
    "Submission Date: 11/29/15\r"
    "Acceptance Date: 1/20/16\r"
    "Contact: john.smith@example.com\r\n"

Replace the carriage returns.

old = {'\r\n','\r'};
new = '\n';
newStr = replace(str,old,new)
newStr = 3×1 string array
    "Submission Date: 11/29/15\n"
    "Acceptance Date: 1/20/16\n"
    "Contact: john.smith@example.com\n"

Input Arguments

collapse all

Input text, specified as a string array, a character vector, or a cell array of character vectors.

Data Types: string | char | cell

Substring to replace, specified as a string array, character vector, or cell array of character vectors.

Data Types: string | char | cell

New substring, specified as a string array, character vector, or cell array of character vectors.

Data Types: string | char | cell

Tips

  • To perform multiple replacements for overlapping patterns, use the strrep function.

Extended Capabilities

Introduced in R2016b

Was this topic helpful?