Method Reference: string.replaceBetween

string: newstr = replaceBetween (str, startPat, endPat, newtext)
string: newstr = replaceBetween (str, startPos, endPos, newtext)
string: newstr = replaceBetween (…, "Boundaries", bounds)

Replace content between start and end boundaries.

newstr = replaceBetween (str, startPat, endPat, newtext) replaces, in each element of the string array str, the text that occurs between the substrings startPat and endPat with newtext, keeping the boundary substrings themselves. startPat and endPat can be string arrays, character vectors, or cell arrays of character vectors. For each element, the first occurrence of startPat is matched and then the first occurrence of endPat that begins after it; if either boundary is not found, the element is returned unchanged.

newstr = replaceBetween (str, startPos, endPos, newtext) replaces the text between the character positions startPos and endPos, inclusive of the characters at those positions, with newtext. startPos and endPos must be positive integers with startPos not exceeding endPos and both within the length of the corresponding element of str.

newstr = replaceBetween (…, "Boundaries", bounds) specifies whether the boundaries are included in or excluded from the replaced text. bounds can be either "inclusive" or "exclusive". When boundaries are given as substrings, the default is "exclusive" and the boundary substrings are preserved; when given as positions, the default is "inclusive" and the characters at those positions are replaced.

startPat/endPat and startPos/endPos must either be scalars, applied to every element of str, or be of the same size as str and applied element-wise. newtext can be a string array, a character vector, or a cell array of character vectors, and must be either a scalar or the same size as str. newstr is a string array of the same size as str. Missing values in str are preserved, and a missing value in newtext makes the corresponding element of newstr missing.

Source Code: string

Example: 1

replaceBetween substitutes the text lying between two delimiters.

 s = string ({'a<x>b'; 'c<y>d'})
s =
  2x1 string array

    "a<x>b"    
    "c<y>d"
 replaceBetween (s, '<', '>', 'Z')
ans =
  2x1 string array

    "a<Z>b"    
    "c<Z>d"