Main Content

extract

从字符串中提取子字符串

自 R2020b 起

说明

示例

newStr = extract(str,pat) 返回 str 中与 pat 指定的模式匹配的任何子字符串。

如果 str 是一个字符串数组或字符向量元胞数组,则该函数将提取 str 的每个元素中的子字符串。如果 pat 是数组,则该函数与多个模式匹配。

示例

newStr = extract(str,pos) 返回 strpos 所指定位置处的字符。

示例

全部折叠

创建一个包含地址的字符串数组。每个地址都以美国邮政编码结尾。

str = ["73 Beacon St., Boston, MA, 02116";
       "1640 Riverside Dr., Hill Valley, CA, 92530";
       "138 Main St., Cambridge, MA, 02138"]
str = 3x1 string
    "73 Beacon St., Boston, MA, 02116"
    "1640 Riverside Dr., Hill Valley, CA, 92530"
    "138 Main St., Cambridge, MA, 02138"

创建一个匹配任意数字序列的模式。

pat = digitsPattern
pat = pattern
  Matching:

    digitsPattern

使用它从地址中提取所有数字序列。

newStr = extract(str,pat)
newStr = 3x2 string
    "73"      "02116"
    "1640"    "92530"
    "138"     "02138"

digitsPattern 模式匹配街道号、公寓号和邮政编码。要仅匹配邮政编码,请创建一个匹配地址末尾的数字序列的模式。

pat = digitsPattern + textBoundary
pat = pattern
  Matching:

    digitsPattern + textBoundary

提取邮政编码。

newStr = extract(str,pat)
newStr = 3x1 string
    "02116"
    "92530"
    "02138"

有关创建模式对象的函数列表,请参阅pattern

创建一个字符串。

str = "All's well that ends well"
str = 
"All's well that ends well"

提取字符串中的第一个字符。

extract(str,1)
ans = 
"A"

提取最后一个字符。

extract(str,strlength(str))
ans = 
"l"

输入参数

全部折叠

输入文本,指定为字符串数组、字符向量或字符向量元胞数组。

搜索模式,指定为下列值之一:

  • 字符串数组

  • 字符向量

  • 字符向量元胞数组

  • pattern 数组

位置,指定为数值数组。

如果 str 是一个字符串数组或字符向量元胞数组,则 pos 可以是与 str 具有相同大小的数值标量或数值数组。

输出参量

全部折叠

输出文本,以字符串数组或字符向量元胞数组形式返回。

如果 str 是字符串数组,则 newStr 也是字符串数组。否则,newStr 为字符向量元胞数组。

版本历史记录

在 R2020b 中推出