Next: , Previous: , Up: Strings   [Contents][Index]


5.5 Manipulating Strings

Octave supports a wide range of functions for manipulating strings. Since a string is just a matrix, simple manipulations can be accomplished using standard operators. The following example shows how to replace all blank characters with underscores.

quote = ...
  "First things first, but not necessarily in that order";
quote( quote == " " ) = "_"
⇒ quote = 
    First_things_first,_but_not_necessarily_in_that_order

For more complex manipulations, such as searching, replacing, and general regular expressions, the following functions come with Octave.

Function File: deblank (s)

Remove trailing whitespace and nulls from s. If s is a matrix, deblank trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element.

Examples:

deblank ("    abc  ")
     ⇒  "    abc"

deblank ([" abc   "; "   def   "])
     ⇒  [" abc  " ; "   def"]

See also: strtrim.

Function File: strtrim (s)

Remove leading and trailing whitespace from s. If s is a matrix, strtrim trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element. For example:

strtrim ("    abc  ")
     ⇒  "abc"

strtrim ([" abc   "; "   def   "])
     ⇒  ["abc  "  ; "  def"]

See also: deblank.

Function File: strtrunc (s, n)

Truncate the character string s to length n. If s is a character matrix, then the number of columns is adjusted. If s is a cell array of strings, then the operation is performed on each cell element and the new cell array is returned.

Function File: findstr (s, t)
Function File: findstr (s, t, overlap)

Return the vector of all positions in the longer of the two strings s and t where an occurrence of the shorter of the two starts. If the optional argument overlap is true, the returned vector can include overlapping positions (this is the default). For example:

findstr ("ababab", "a")
     ⇒ [1, 3, 5];
findstr ("abababa", "aba", 0)
     ⇒ [1, 5]

Caution: findstr is scheduled for deprecation. Use strfind in all new code.

See also: strfind, strmatch, strcmp, strncmp, strcmpi, strncmpi, find.

Function File: idx = strchr (str, chars)
Function File: idx = strchr (str, chars, n)
Function File: idx = strchr (str, chars, n, direction)
Function File: [i, j] = strchr (…)

Search for the string str for occurrences of characters from the set chars. The return value(s), as well as the n and direction arguments behave identically as in find.

This will be faster than using regexp in most cases.

See also: find.

Function File: index (s, t)
Function File: index (s, t, direction)

Return the position of the first occurrence of the string t in the string s, or 0 if no occurrence is found. s may also be a string array or cell array of strings.

For example:

index ("Teststring", "t")
    ⇒ 4

If direction is "first", return the first element found. If direction is "last", return the last element found.

See also: find, rindex.

Function File: rindex (s, t)

Return the position of the last occurrence of the character string t in the character string s, or 0 if no occurrence is found. s may also be a string array or cell array of strings.

For example:

rindex ("Teststring", "t")
     ⇒ 6

The rindex function is equivalent to index with direction set to "last".

See also: find, index.

Built-in Function: idx = strfind (str, pattern)
Built-in Function: idx = strfind (cellstr, pattern)
Built-in Function: idx = strfind (…, "overlaps", val)

Search for pattern in the string str and return the starting index of every such occurrence in the vector idx.

If there is no such occurrence, or if pattern is longer than str, then idx is the empty array []. The optional argument "overlaps" determines whether the pattern can match at every position in str (true), or only for unique occurrences of the complete pattern (false). The default is true.

If a cell array of strings cellstr is specified then idx is a cell array of vectors, as specified above.

Examples:

strfind ("abababa", "aba")
     ⇒ [1, 3, 5]

strfind ("abababa", "aba", "overlaps", false)
     ⇒ [1, 5]

strfind ({"abababa", "bebebe", "ab"}, "aba")
     ⇒
        {
          [1,1] =

             1   3   5

          [1,2] = [](1x0)
          [1,3] = [](1x0)
        }

See also: findstr, strmatch, regexp, regexpi, find.

Function File: str = strjoin (cstr)
Function File: str = strjoin (cstr, delimiter)

Join the elements of the cell-string array, cstr, into a single string.

If no delimiter is specified, the elements of cstr separated by a space.

If delimiter is specified as a string, the cell-string array is joined using the string. Escape sequences are supported.

If delimiter is a cell-string array whose length is one less than cstr, then the elements of cstr are joined by interleaving the cell-string elements of delimiter. Escape sequences are not supported.

strjoin ({'Octave','Scilab','Lush','Yorick'}, '*')
      ⇒ 'Octave*Scilab*Lush*Yorick'

See also: strsplit.

Function File: strmatch (s, A)
Function File: strmatch (s, A, "exact")

Return indices of entries of A which begin with the string s. The second argument A must be a string, character matrix, or a cell array of strings. If the third argument "exact" is not given, then s only needs to match A up to the length of s. Trailing spaces and nulls in s and A are ignored when matching.

For example:

strmatch ("apple", "apple juice")
     ⇒ 1

strmatch ("apple", ["apple  "; "apple juice"; "an apple"])
     ⇒ [1; 2]

strmatch ("apple", ["apple  "; "apple juice"; "an apple"], "exact")
     ⇒ [1]

Caution: strmatch is scheduled for deprecation. Use strncmp (normal case), or strcmp ("exact" case), or regexp in all new code.

See also: strfind, findstr, strcmp, strncmp, strcmpi, strncmpi, find.

Function File: [tok, rem] = strtok (str)
Function File: [tok, rem] = strtok (str, delim)

Find all characters in the string str up to, but not including, the first character which is in the string delim. If rem is requested, it contains the remainder of the string, starting at the first delimiter. Leading delimiters are ignored. If delim is not specified, whitespace is assumed. str may also be a cell array of strings in which case the function executes on every individual string and returns a cell array of tokens and remainders.

Examples:

strtok ("this is the life")
     ⇒ "this"

[tok, rem] = strtok ("14*27+31", "+-*/")
     ⇒
        tok = 14
        rem = *27+31

See also: index, strsplit, strchr, isspace.

Function File: [cstr] = strsplit (s)
Function File: [cstr] = strsplit (s, del)
Function File: [cstr] = strsplit (…, name, value)
Function File: [cstr, matches] = strsplit (…)

Split the string s using the delimiters specified by del and return a cell-string array of sub-strings. If a delimiter is not specified the string, s, is split at whitespace. The delimiter, del may be a string, a scalar cell-string, or cell-string array. del must be a cell-string array. By default, consecutive delimiters in the input string, s, are collapsed into one.

The second output, matches, returns the delmiters which were matched in the original string.

Example:

strsplit ("a b c")
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = c
          }

strsplit ("a,b,c", ",")
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = c
          }

strsplit ("a foo b,bar c", {"\s", "foo", "bar"})
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = c
          }

strsplit ("a,,b, c", {",", " "}, false)
      ⇒
          {
            [1,1] = a
            [1,2] = 
            [1,3] = b
            [1,4] = 
            [1,5] = c
          }

Supported name/value pair arguments are;

Example:

strsplit ("a foo b,bar c", ",|\\s|foo|bar", "delimitertype", "regularexpression")
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = c
          }

strsplit ("a,,b, c", "[, ]", false, "delimitertype", "regularexpression")
      ⇒
          {
            [1,1] = a
            [1,2] = 
            [1,3] = b
            [1,4] = 
            [1,5] = c
          }

strsplit ("a,\t,b, c", {',', '\s'}, "delimitertype", "regularexpression")
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = c
          }

strsplit ("a,\t,b, c", {',', ' ', '\t'}, "collapsedelimiters", false)
      ⇒
          {
            [1,1] = a
            [1,2] = 
            [1,3] = 
            [1,4] = b
            [1,5] = 
            [1,6] = c
          }

See also: ostrsplit, strjoin, strtok, regexp.

Function File: [cstr] = ostrsplit (s, sep)
Function File: [cstr] = ostrsplit (s, sep, strip_empty)

Split the string s using one or more separators sep and return a cell array of strings. Consecutive separators and separators at boundaries result in empty strings, unless strip_empty is true. The default value of strip_empty is false.

2-D character arrays are split at separators and at the original column boundaries.

Example:

ostrsplit ("a,b,c", ",")
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = c
          }

ostrsplit (["a,b" ; "cde"], ",")
      ⇒
          {
            [1,1] = a
            [1,2] = b
            [1,3] = cde
          }

See also: strsplit, strtok.

Function File: [a, …] = strread (str)
Function File: [a, …] = strread (str, format)
Function File: [a, …] = strread (str, format, format_repeat)
Function File: [a, …] = strread (str, format, prop1, value1, …)
Function File: [a, …] = strread (str, format, format_repeat, prop1, value1, …)

Read data from a string.

The string str is split into words that are repeatedly matched to the specifiers in format. The first word is matched to the first specifier, the second to the second specifier and so forth. If there are more words than specifiers, the process is repeated until all words have been processed.

The string format describes how the words in str should be parsed. It may contain any combination of the following specifiers:

%s

The word is parsed as a string.

%f
%n

The word is parsed as a number and converted to double.

%d
%u

The word is parsed as a number and converted to int32.

%*', '%*f', '%*s

The word is skipped.

For %s and %d, %f, %n, %u and the associated %*s … specifiers an optional width can be specified as %Ns, etc. where N is an integer > 1. For %f, format specifiers like %N.Mf are allowed.

literals

In addition the format may contain literal character strings; these will be skipped during reading.

Parsed word corresponding to the first specifier are returned in the first output argument and likewise for the rest of the specifiers.

By default, format is "%f", meaning that numbers are read from str. This will do if str contains only numeric fields.

For example, the string

str = "\
Bunny Bugs   5.5\n\
Duck Daffy  -7.5e-5\n\
Penguin Tux   6"

can be read using

[a, b, c] = strread (str, "%s %s %f");

Optional numeric argument format_repeat can be used for limiting the number of items read:

-1

(default) read all of the string until the end.

N

Read N times nargout items. 0 (zero) is an acceptable value for format_repeat.

The behavior of strread can be changed via property-value pairs. The following properties are recognized:

"commentstyle"

Parts of str are considered comments and will be skipped. value is the comment style and can be any of the following.

  • "shell" Everything from # characters to the nearest end-of-line is skipped.
  • "c" Everything between /* and */ is skipped.
  • "c++" Everything from // characters to the nearest end-of-line is skipped.
  • "matlab" Everything from % characters to the nearest end-of-line is skipped.
  • user-supplied. Two options: (1) One string, or 1x1 cell string: Skip everything to the right of it; (2) 2x1 cell string array: Everything between the left and right strings is skipped.
"delimiter"

Any character in value will be used to split str into words (default value = any whitespace).

"emptyvalue":

Value to return for empty numeric values in non-whitespace delimited data. The default is NaN. When the data type does not support NaN (int32 for example), then default is zero.

"multipledelimsasone"

Treat a series of consecutive delimiters, without whitespace in between, as a single delimiter. Consecutive delimiter series need not be vertically "aligned".

"treatasempty"

Treat single occurrences (surrounded by delimiters or whitespace) of the string(s) in value as missing values.

"returnonerror"

If value true (1, default), ignore read errors and return normally. If false (0), return an error.

"whitespace"

Any character in value will be interpreted as whitespace and trimmed; the string defining whitespace must be enclosed in double quotes for proper processing of special characters like \t. The default value for whitespace = " \b\r\n\t" (note the space). Unless whitespace is set to ” (empty) AND at least one "%s" format conversion specifier is supplied, a space is always part of whitespace.

When the number of words in str doesn’t match an exact multiple of the number of format conversion specifiers, strread’s behavior depends on the last character of str:

last character = "\n"

Data columns are padded with empty fields or Nan so that all columns have equal length

last character is not "\n"

Data columns are not padded; strread returns columns of unequal length

See also: textscan, textread, load, dlmread, fscanf.

Built-in Function: newstr = strrep (str, ptn, rep)
Built-in Function: newstr = strrep (cellstr, ptn, rep)
Built-in Function: newstr = strrep (…, "overlaps", val)

Replace all occurrences of the pattern ptn in the string str with the string rep and return the result.

The optional argument "overlaps" determines whether the pattern can match at every position in str (true), or only for unique occurrences of the complete pattern (false). The default is true.

s may also be a cell array of strings, in which case the replacement is done for each element and a cell array is returned.

Example:

strrep ("This is a test string", "is", "&%$")
    ⇒  "Th&%$ &%$ a test string"

See also: regexprep, strfind, findstr.

Function File: substr (s, offset)
Function File: substr (s, offset, len)

Return the substring of s which starts at character number offset and is len characters long.

Position numbering for offsets begins with 1. If offset is negative, extraction starts that far from the end of the string.

If len is omitted, the substring extends to the end of S. A negative value for len extracts to within len characters of the end of the string

Examples:

substr ("This is a test string", 6, 9)
     ⇒ "is a test"
substr ("This is a test string", -11)
     ⇒ "test string"
substr ("This is a test string", -11, -7)
     ⇒ "test"

This function is patterned after the equivalent function in Perl.

Built-in Function: [s, e, te, m, t, nm, sp] = regexp (str, pat)
Built-in Function: […] = regexp (str, pat, "opt1", …)

Regular expression string matching. Search for pat in str and return the positions and substrings of any matches, or empty values if there are none.

The matched pattern pat can include any of the standard regex operators, including:

.

Match any character

* + ? {}

Repetition operators, representing

*

Match zero or more times

+

Match one or more times

?

Match zero or one times

{n}

Match exactly n times

{n,}

Match n or more times

{m,n}

Match between m and n times

[…] [^…]

List operators. The pattern will match any character listed between "[" and "]". If the first character is "^" then the pattern is inverted and any character except those listed between brackets will match.

Escape sequences defined below can also be used inside list operators. For example, a template for a floating point number might be [-+.\d]+.

() (?:)

Grouping operator. The first form, parentheses only, also creates a token.

|

Alternation operator. Match one of a choice of regular expressions. The alternatives must be delimited by the grouping operator () above.

^ $

Anchoring operators. Requires pattern to occur at the start (^) or end ($) of the string.

In addition, the following escaped characters have special meaning.

\d

Match any digit

\D

Match any non-digit

\s

Match any whitespace character

\S

Match any non-whitespace character

\w

Match any word character

\W

Match any non-word character

\<

Match the beginning of a word

\>

Match the end of a word

\B

Match within a word

Implementation Note: For compatibility with MATLAB, ordinary escape sequences (e.g., "\n" => newline) are processed in pat regardless of whether pat has been defined within single quotes. Use a second backslash to stop interpolation of the escape sequence (e.g., "\\n") or use the regexptranslate function.

The outputs of regexp default to the order given below

s

The start indices of each matching substring

e

The end indices of each matching substring

te

The extents of each matched token surrounded by (…) in pat

m

A cell array of the text of each match

t

A cell array of the text of each token matched

nm

A structure containing the text of each matched named token, with the name being used as the fieldname. A named token is denoted by (?<name>…).

sp

A cell array of the text not returned by match, i.e., what remains if you split the string based on pat.

Particular output arguments, or the order of the output arguments, can be selected by additional opt arguments. These are strings and the correspondence between the output arguments and the optional argument are

'start's
'end'e
'tokenExtents'te
'match'm
'tokens't
'names'nm
'split'sp

Additional arguments are summarized below.

once

Return only the first occurrence of the pattern.

matchcase

Make the matching case sensitive. (default)

Alternatively, use (?-i) in the pattern.

ignorecase

Ignore case when matching the pattern to the string.

Alternatively, use (?i) in the pattern.

stringanchors

Match the anchor characters at the beginning and end of the string. (default)

Alternatively, use (?-m) in the pattern.

lineanchors

Match the anchor characters at the beginning and end of the line.

Alternatively, use (?m) in the pattern.

dotall

The pattern . matches all characters including the newline character. (default)

Alternatively, use (?s) in the pattern.

dotexceptnewline

The pattern . matches all characters except the newline character.

Alternatively, use (?-s) in the pattern.

literalspacing

All characters in the pattern, including whitespace, are significant and are used in pattern matching. (default)

Alternatively, use (?-x) in the pattern.

freespacing

The pattern may include arbitrary whitespace and also comments beginning with the character ‘#’.

Alternatively, use (?x) in the pattern.

noemptymatch

Zero-length matches are not returned. (default)

emptymatch

Return zero-length matches.

regexp ('a', 'b*', 'emptymatch') returns [1 2] because there are zero or more 'b' characters at positions 1 and end-of-string.

See also: regexpi, strfind, regexprep.

Built-in Function: [s, e, te, m, t, nm, sp] = regexpi (str, pat)
Built-in Function: […] = regexpi (str, pat, "opt1", …)

Case insensitive regular expression string matching. Search for pat in str and return the positions and substrings of any matches, or empty values if there are none. See regexp, for details on the syntax of the search pattern.

See also: regexp.

Built-in Function: outstr = regexprep (string, pat, repstr)
Built-in Function: outstr = regexprep (string, pat, repstr, "opt1", …)

Replace occurrences of pattern pat in string with repstr.

The pattern is a regular expression as documented for regexp. See regexp.

The replacement string may contain $i, which substitutes for the ith set of parentheses in the match string. For example,

regexprep ("Bill Dunn", '(\w+) (\w+)', '$2, $1')

returns "Dunn, Bill"

Options in addition to those of regexp are

once

Replace only the first occurrence of pat in the result.

warnings

This option is present for compatibility but is ignored.

Implementation Note: For compatibility with MATLAB, ordinary escape sequences (e.g., "\n" => newline) are processed in both pat and repstr regardless of whether they were defined within single quotes. Use a second backslash to stop interpolation of the escape sequence (e.g., "\\n") or use the regexptranslate function.

See also: regexp, regexpi, strrep.

Function File: regexptranslate (op, s)

Translate a string for use in a regular expression. This may include either wildcard replacement or special character escaping. The behavior is controlled by op which can take the following values

"wildcard"

The wildcard characters ., *, and ? are replaced with wildcards that are appropriate for a regular expression. For example:

regexptranslate ("wildcard", "*.m")
     ⇒ ".*\.m"
"escape"

The characters $.?[], that have special meaning for regular expressions are escaped so that they are treated literally. For example:

regexptranslate ("escape", "12.5")
     ⇒ "12\.5"

See also: regexp, regexpi, regexprep.

Function File: untabify (t)
Function File: untabify (t, tw)
Function File: untabify (t, tw, deblank)

Replace TAB characters in t, with spaces. The tab width is specified by tw, or defaults to eight. The input, t, may be either a 2-D character array, or a cell array of character strings. The output is the same class as the input.

If the optional argument deblank is true, then the spaces will be removed from the end of the character data.

The following example reads a file and writes an untabified version of the same file with trailing spaces stripped.

fid = fopen ("tabbed_script.m");
text = char (fread (fid, "uchar")');
fclose (fid);
fid = fopen ("untabified_script.m", "w");
text = untabify (strsplit (text, "\n"), 8, true);
fprintf (fid, "%s\n", text{:});
fclose (fid);

See also: strjust, strsplit, deblank.


Next: , Previous: , Up: Strings   [Contents][Index]