Method Reference: string.extractBefore

string: newstr = extractBefore (str, pat)
string: newstr = extractBefore (str, pos)

Extract the substring before a position or pattern.

newstr = extractBefore (str, pat) returns, for each element of str, the part of the text that precedes the first occurrence of pat, excluding pat itself. pat can be a string array, a character vector, or a cell array of character vectors, and must either be a scalar, applied to every element of str, or be of the same size as str and applied element-wise. If pat is not found in an element, the corresponding element of newstr is a missing value.

newstr = extractBefore (str, pos) returns the part of each element of str that precedes the character position pos, that is, from the start up to pos-1. pos must be a positive integer that is 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.

Source Code: string

Example: 1

extractBefore returns the part of each string before the first occurrence of a substring — for example a file's base name before its extension.

 files = string ({'cat.txt'; 'dog.csv'})
files =
  2x1 string array

    "cat.txt"    
    "dog.csv"
 extractBefore (files, '.')
ans =
  2x1 string array

    "cat"    
    "dog"