strfind

Finds the start positions of a pattern inside text.

Category: Language Fundamentals > Data Types

Syntax

k = strfind(str, pat)

Returns the indices where pat starts in str.

Description

The search is case sensitive and literal, with no wildcards. Matches may overlap: strfind('aaa', 'aa') returns [1 2]. If pat is longer than str or is empty, the result is empty.

To test whether a pattern occurs at all, contains is simpler; to extract or replace with patterns, use regexp and regexprep.

Input arguments

str
Character vector or string to search.
pat
Literal text to look for.

Output arguments

k
Row vector of starting indices, in increasing order; empty if there is no match.

Example

Positions and overlap

strfind('abracadabra', 'abra')
strfind('aaa', 'aa')
isempty(strfind('abc', 'z'))
Output
ans = 1×2

     1     8
ans = 1×2

     1     2
ans = logical
   1

See also

contains regexp strrep extractBefore startsWith