How to extract a number from a string array?

4 次查看(过去 30 天)
I have a string array of values that look like this: "(164) - (165)" "(165) - (166)" "(165) - (166)" How can extract the first three digit value only so that I get a matrix that is 164 165 165
  4 个评论
Dayne Coleman
Dayne Coleman 2018-6-21
Yes, I have tried sscanf(_). I don't know if it's a problem with my indexing or the function itself. Here is what I have:
>> whos str_node
Name Size Bytes Class Attributes
str_node 92x1 7248 string
node=sscanf(str_node(:,1),'%f')
I'm getting an error that reads:
"First argument must be a string scalar or character vector."
Dayne Coleman
Dayne Coleman 2018-6-21
I got it to work using the strtok(_) function below. Let me know if there are faster, more efficient ways of doing it.
[token,remain]=strtok(str_node,'0,1,2,3,4,5,6,7,8,9');
parsed_node=strtok(remain,')');
node=str2double(parsed_node(:));

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2018-6-21
编辑:Stephen23 2018-6-21
"How can extract the first three digit value only so that I get a matrix that is 164 165 165"
With a simple application of regexp and str2double:
>> C = {'(164) - (165)','(165) - (166)','(165) - (166)'};
>> str2double(regexp(C,'\d{3}','match','once'))
ans =
164 165 165

更多回答(1 个)

Juan Fernandez
Juan Fernandez 2018-6-21
I searched through older questions and found a similar one from 2012. The solution requires the use of regexp(_). Here's my implementation.
str1 = '(164) - (165)';
str2 = '(165) - (166)';
str3 = '(165) - (166)';
strs = {str1,str2,str3};
output = zeros(length(strs),1);
for iter=1:length(strs)
num_strs = regexp(strs{iter},'\d*','Match');
output(iter) = str2double(num_strs{1});
end

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by