在 MATLAB 中从字符串中提取数字
Extract numbers from string in MATLAB
我正在使用 sscanf 从字符串中提取数字。字符串通常采用以下形式:
'44 ppm'
'10 gallons'
'23.4 inches'
但有时它们的形式是:
'<1 ppm'
如果我使用下面的代码:
x = sscanf('1 ppm','%f')
我得到
的输出
1
但是如果我在前面加上小于号:
x = sscanf('<1 ppm','%f')
我得到:
[]
我如何编写这段代码才能实际生成一个数字?我还不确定它应该打印什么数字...但我们暂时只说它应该打印 1 。
您可以使用 regexp
:
s= '<1 ppm';
x=regexp(s, '.*?(\d+(\.\d+)*)', 'tokens' )
x{1}
演示:
>> s= {'44 ppm', '10 gallons', '23.4 inches', '<1 ppm' } ;
>> x = regexp(s, '.*?(\d+(\.\d+)*)', 'tokens' );
>> cellfun( @(x) disp(x{1}), x ) % Demo for all
'44'
'10'
'23.4'
'1'
我正在使用 sscanf 从字符串中提取数字。字符串通常采用以下形式:
'44 ppm'
'10 gallons'
'23.4 inches'
但有时它们的形式是:
'<1 ppm'
如果我使用下面的代码:
x = sscanf('1 ppm','%f')
我得到
的输出1
但是如果我在前面加上小于号:
x = sscanf('<1 ppm','%f')
我得到:
[]
我如何编写这段代码才能实际生成一个数字?我还不确定它应该打印什么数字...但我们暂时只说它应该打印 1 。
您可以使用 regexp
:
s= '<1 ppm';
x=regexp(s, '.*?(\d+(\.\d+)*)', 'tokens' )
x{1}
演示:
>> s= {'44 ppm', '10 gallons', '23.4 inches', '<1 ppm' } ;
>> x = regexp(s, '.*?(\d+(\.\d+)*)', 'tokens' );
>> cellfun( @(x) disp(x{1}), x ) % Demo for all
'44'
'10'
'23.4'
'1'