reading a number from a string

조회 수: 25 (최근 30일)
Jim O'Doherty
Jim O'Doherty 2013년 7월 17일
Hi all,
I've got a set of strings that are either [1x80] or [1x81], and I'm trying to parse an increasing number from the string. My problem occurs when the length of the string changes due to a number increment. A sample of the strings is:
str='(0020,0013) IS [98] # 2, 1 InstanceNumber'
str='(0020,0013) IS [99] # 2, 1 InstanceNumber'
str='(0020,0013) IS [100] # 2, 1 InstanceNumber'
str='(0020,0013) IS [101] # 2, 1 InstanceNumber'
I'd like to be able to parse the 98, 99, 100, 101 etc from the strings.
The format of the strings is identical, apart from the increasing number.
Currently I can use the following, which fails for the double digit numbers but works for the triple digits:
num=sscanf(str, '%*5c, %*10c %3s')
Any idea how I could make sure I always get the increasing number regardless of its length? It always starts at the same position and is contained in the square brackets.
Cheers, Jim

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 17일
str='(0020,0013) IS [98] # 2, 1 InstanceNumber'
pattern='(?<=\[)\d+(?=\])'
out=regexp(str,pattern,'match')
  댓글 수: 1
Jim O'Doherty
Jim O'Doherty 2013년 7월 18일
3 very good answers which all work perfectly for what I need
Thank you all very much!
Jim

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Daniel Pereira
Daniel Pereira 2013년 7월 17일
x = sscanf(str,'(%d,%d) IS [%d] %s %d,%d %s');
num = x([1 2 3 5 6]);
when using
str='(0020,0013) IS [98] # 2, 1 InstanceNumber'
gives
20
13
98
2
1
and when using
str2='(0020,0013) IS [100] # 2, 1 InstanceNumber'
gives
20
13
100
2
1
hope it helps

Image Analyst
Image Analyst 2013년 7월 17일
Try this:
index = strfind(str, ']')-1
theNumber = str2double(str(17:index))

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by