extractBetween — Extract substrings between boundary markers in MATLAB and RunMat.
extractBetween(text, start, stop) returns text between two boundary markers. Numeric positions accept single, double, and all eight integer classes as one-based structural controls.
Syntax
newText = extractBetween(str, start, end)
newText = extractBetween(str, start, end, Name, Value, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
str | Any | Yes | — | Input text scalar/array/cell. |
start | Any | Yes | — | Start boundary marker text or positive integer position(s). |
end | Any | Yes | — | End boundary marker text or positive integer position(s). |
Name | StringScalar | Yes | — | Option name (`Boundaries`). |
Value | Any | Variadic | — | Option value and additional Name/Value pairs. |
Returns
| Name | Type | Description |
|---|---|---|
newText | Any | Extracted text preserving scalar/array/cell text container semantics. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:extractBetween:InvalidInput | First argument is not a string array, character array, or cell array of text scalars. | extractBetween: first argument must be a string array, character array, or cell array of character vectors |
RunMat:extractBetween:BoundaryType | Start/end boundaries are mixed text/numeric domains or use unsupported boundary types. | extractBetween: start and end arguments must both be text or both be numeric positions |
RunMat:extractBetween:PositionType | Numeric boundary positions are not positive finite integers. | extractBetween: position arguments must be positive integers |
RunMat:extractBetween:NameValuePair | Name/value options are not supplied in complete pairs. | extractBetween: name-value arguments must appear in pairs |
RunMat:extractBetween:OptionName | An option name other than `Boundaries` was supplied. | extractBetween: unrecognized parameter name |
RunMat:extractBetween:OptionValue | `Boundaries` option value is not `inclusive` or `exclusive`. | extractBetween: 'Boundaries' must be either 'inclusive' or 'exclusive' |
RunMat:extractBetween:CellElement | Cell text input/boundary contains non-text values or non-row char arrays. | extractBetween: cell array elements must be string scalars or character vectors |
RunMat:extractBetween:SizeMismatch | Text/boundary inputs are not broadcast-compatible for extraction. | extractBetween: boundary sizes must be compatible with the text input |
RunMat:extractBetween:InternalError | Internal output construction failed. | extractBetween: internal error |
How extractBetween works
- Documented text input is a string array, character vector, or cell array of character vectors. String input returns string output; character-vector and cellstr input return cell arrays of character vectors.
- Boundary inputs can be text or numeric positions. Both boundaries in a call must use the same kind of input; mixing text and numeric markers raises a size/type error.
- Scalar boundaries apply to every text element. Nonscalar boundaries must have exactly the same shape as the text input in strict compatibility mode; broader implicit broadcasting is a RunMat extension.
- The
'Boundaries'name-value pair controls inclusivity. Text markers default to exclusive extraction, while numeric positions default to inclusive behaviour. Values are case-insensitive and must be'exclusive'or'inclusive'. - Missing string scalars propagate: if the text, start marker, or end marker is
<missing>, the result is also<missing>. - When the start or end boundary cannot be located,
extractBetweenreturns an empty string (or an appropriately padded empty row for character arrays). - Numeric positions use 1-based indexing and are read directly from native single, double, or integer storage. Inputs must be positive integers; stop positions beyond the text length are clamped by the current implementation.
- Row-wise character matrices, cells containing string scalars, and resident numeric positions are separately declared RunMat extensions. Integer, logical, and complex text inputs reject before provider access.
Does RunMat run extractBetween on the GPU?
Text manipulation executes on the CPU. RunMat extension mode can gather resident numeric position controls and leaves results on the host. No Accelerate provider hooks are registered, and numeric resident text is rejected before provider access.
Examples
Extract text between words in a string
txt = "RunMat accelerates MATLAB workloads";
segment = extractBetween(txt, "RunMat ", " workloads")Expected output:
segment = "accelerates MATLAB"Include boundary markers with the 'Boundaries' option
path = "snapshots/run/fusion.mat";
withMarkers = extractBetween(path, "snapshots/", ".mat", "Boundaries", "inclusive")Expected output:
withMarkers = "snapshots/run/fusion.mat"Use numeric positions for 1-based indexing
name = "Accelerator";
middle = extractBetween(name, 3, 7)Expected output:
middle = "celer"Apply scalar text markers to each element of a string array
files = ["runmat_accel.rs", "runmat_gc.rs"; "runmat_plot.rs", "runmat_cli.rs"];
stems = extractBetween(files, "runmat_", ".rs")Expected output:
stems = 2×2 string
"accel" "gc"
"plot" "cli"Extracting text row by row from a character matrix
chars = char("Device<GPU>", "Planner<Fusion>");
tokens = extractBetween(chars, "<", ">")Expected output:
tokens =
2×6 char array
"GPU "
"Fusion"Extracting text from mixed cell contents
C = {'<missing>', 'A[B]C'; "Planner <Fusion>", "Device<GPU>"};
out = extractBetween(C, "<", ">")Expected output:
out =
2×2 cell array
{'<missing>'} {'B'}
{"Fusion"} {"GPU"}Handle missing strings without throwing errors
txt = ["<missing>", "Planner<GPU>"];
tokens = extractBetween(txt, "<", ">")Expected output:
tokens = 1×2 string
"<missing>" "GPU"Using extractBetween with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how extractBetween changes the result.
Run a small extractBetween example, explain the result, then change one input and compare the output.
FAQ
Which argument types does extractBetween accept?⌄
The documented first argument is a string array, character vector, or cell array of character vectors. Boundaries can be text or numeric positions. Numeric positions accept single, double, int8, int16, int32, int64, uint8, uint16, uint32, and uint64. RunMat extension mode additionally admits row-wise character matrices and broader text cells.
Can the start and end arguments mix text and numeric positions?⌄
No. Both boundaries must be text markers or both must be numeric positions. Mixing types raises a size/type error, mirroring MATLAB.
What happens when a boundary is not found?⌄
The current RunMat implementation returns empty extracted text. String inputs produce empty strings; documented non-string inputs produce character vectors inside cell output.
How does 'Boundaries','inclusive' behave with numeric positions?⌄
Inclusive mode returns the substring that includes both indices. Exclusive mode removes the characters at the specified start and end positions, yielding the text strictly between the two indices.
Does extractBetween support implicit expansion?⌄
Documented compatibility permits scalar boundaries or boundaries exactly the same size as the text input. Broader broadcast-compatible shapes require RunMat extension mode.
Are GPU inputs supported?⌄
There is no provider kernel. Resident numeric positions require RunMat extension mode, are gathered, and produce host text output. Numeric resident values are never accepted as the text argument.
Related Strings functions
Transform
append · deblank · erase · eraseBetween · erasePunctuation · eraseURLs · extractAfter · extractBefore · insertAfter · insertBefore · join · lower · pad · replace · replaceBetween · reverse · split · splitlines · strcat · strip · strjoin · strjust · strrep · strsplit · strtrim · upper
Text Analytics
addDependencyDetails · addEntityDetails · addLemmaDetails · addPartOfSpeechDetails · addSentenceDetails · addTypeDetails · bagOfNgrams · bagOfWords · cosineSimilarity · doc2sequence · encode · extractFileText · extractHTMLText · fastTextWordEmbedding · findElement · getAttribute · htmlTree · ind2word · isVocabularyWord · normalizeWords · readWordEmbedding · removeLongWords · removeShortWords · removeStopWords · removeWords · stopWords · tokenDetails · tokenizedDocument · trainWordEmbedding · vaderSentimentScores · vec2word · word2ind · word2vec · wordEncoding · writeWordEmbedding
Core
blanks · char · compose · convertCharsToStrings · convertContainedStringsToChars · convertStringsToChars · genvarname · int2str · isletter · isspace · isStringScalar · isstrprop · mat2str · native2unicode · newline · num2str · sprintf · sscanf · str2double · str2num · strcmp · strcmpi · string · string.empty · strings · strlength · strncmp · strncmpi · strtok · unicode2native
Search
contains · endsWith · matches · startsWith · strfind
Pattern
digitsPattern · lettersPattern · pattern · regexpPattern · textBoundary · wildcardPattern
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how extractBetween is executed, line by line, in Rust.
- View the source for extractBetween in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.