Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

strrep

查找并替换子字符串

说明

示例

newStr = strrep(str,old,new)str 中出现的所有 old 都替换为 new

如果任何输入参数是非标量字符串数组或字符向量元胞数组,则其他输入参数的大小必须兼容。

示例

全部折叠

创建字符向量并替换其中的子字符串。

chr = 'The quick brown fox'
chr = 
'The quick brown fox'
newChr = strrep(chr,'quick','sly')
newChr = 
'The sly brown fox'

创建一个字符串数组。

str = ["the quick brown fox";
       "and the lazy dog"]
str = 2x1 string
    "the quick brown fox"
    "and the lazy dog"

替换每个数组元素中的子字符串。

newStr = strrep(str,'the','a')
newStr = 2x1 string
    "a quick brown fox"
    "and a lazy dog"

将元胞数组中的占位符内容 '___' 替换为第二个元胞数组中的不同值。

C1 = {'Date Received: ___';
      'Date Accepted: ___'};
old = '___';
new = {'2016-09-06';
       '2016-10-11'};
C2 = strrep(C1,old,new)
C2 = 2x1 cell
    {'Date Received: 2016-09-06'}
    {'Date Accepted: 2016-10-11'}

创建具有重复、重叠模式的字符向量。使用 strrepreplaceregexprep 函数比较结果以取代该模式。

repeats = 'abc 2 def 22 ghi 222 jkl 2222'
repeats = 
'abc 2 def 22 ghi 222 jkl 2222'

使用 strfind 函数查找重复模式 '22' 的索引。strfind 会查找模式的所有实例,包括重叠的实例。

indices = strfind(repeats, '22')
indices = 1×6

    11    18    19    26    27    28

使用 strrep 替换 '22'。当您使用 strrep 时,它会替换 strfind 标识的每个实例。

using_strrep = strrep(repeats, '22', '*')
using_strrep = 
'abc 2 def * ghi ** jkl ***'

使用 replace 替换 '22'。它不会替换 strrep 替换的每个实例。

using_replace = replace(repeats, '22', '*')
using_replace = 
'abc 2 def * ghi *2 jkl **'

使用 regexprep 替换 '22'。结果与使用 replace 函数的结果相同。

using_regexprep = regexprep(repeats, '22', '*')
using_regexprep = 
'abc 2 def * ghi *2 jkl **'

strrep 在替换任何实例之前先查找模式的所有实例。但是,replaceregexprep 函数在文本中找到模式的实例后会立即进行替换。

输入参数

全部折叠

输入文本,指定为字符串数组、字符向量或字符向量元胞数组。

数据类型: string | char | cell

要替换的子字符串,指定为字符串数组、字符向量或字符向量元胞数组。

数据类型: string | char | cell

新的子字符串,指定为字符串数组、字符向量或字符向量元胞数组。

数据类型: string | char | cell

算法

  • strrep 函数不会查找空字符向量或空字符串进行替换。即,当 strold 均包含空字符向量 ('') 或空字符串 ("") 时,strrep 不会将空字符向量或字符串替换为 new 的内容。

  • 在替换文本之前,strrep 会像 strfind 函数一样查找 str 中的所有 old 实例。对于重叠模式,strrep 执行多次替换。

扩展功能

版本历史记录

在 R2006a 之前推出