MATLAB从字符串中读取所有数字 [英] MATLAB reading all numbers from a string

查看:2491
本文介绍了MATLAB从字符串中读取所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从字符串中读取未知数量的数字值.

I'm trying to read an unknown number of numeric values from a string.

例如:

line = 'bla bal bli : 3 5 12 15 266'

我尝试了sscanf,但是它要求我提前知道字符串中有多少个数字.

I tried sscanf but it requires I know how many numbers are in the string ahead of time.

推荐答案

如果要从字符串中提取整数,则可以使用正则表达式:

If you want to extract integer numbers from the strings, you can use a regular expression:

  1. 要获取数字作为字符串的单元格数组:

  1. To get the numbers as a cell array of strings:

>> line = 'bla bal bli : 3 5 12 15 266';
>> regexp(line,'(?<!\d)(\d)+(?!\d)','match')
ans = 
    '3'    '5'    '12'    '15'    '266'

  • 要获取数字作为数字矢量:

  • To get the numbers as a numeric vector:

    >> str2double(regexp(line,'(?<!\d)(\d)+(?!\d)','match'))
    ans =
         3     5    12    15   266
    

  • 这篇关于MATLAB从字符串中读取所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆