Interpret string to form sequence of numbers

I want to see if something like this already has been discussed (so I am not reinventing the wheel). Basically, I will read in a string (from a GUI) that defines a sequence of numbers, where (as an example):
temp_str = '1,2,4-9,12-20(2)';
And then, after interpreting the contents of the string, the output to the code would yield a numeric array with values:
temp_seq = [1,2,4,5,6,7,8,9,12,14,16,18,20];
Has anyone come across a thread that discusses something similar to this? If so, let me know as I would like to clean up and make my version more efficient.

 채택된 답변

David Young
David Young 2011년 12월 4일

2 개 추천

Could you ask the user to enter 4:9 instead of 4-9, and 12:2:20 instead of 12-20(2)? If so (and also if you can trust the user not to enter functions that might have side effects instead of numbers), there's a one-liner that will do it:
>> temp_str = '1,2,4:9,12:2:20';
>> temp_seq = str2num(temp_str);
temp_seq =
Columns 1 through 8
1 2 4 5 6 7 8 9
Columns 9 through 13
12 14 16 18 20
If you want to stick to your original hyphen-based input format, it's still pretty easy to use regexprep to switch it to the colon-operator format.
EDIT: regexprep code added
To do this translation, assuming all the input numbers are positive integers, you could use:
>> temp_str2 = regexprep(temp_str, {'-' ':(\d+)\((\d+)\)'}, {':', ':$2:$1'})
This all assumes that the user sticks to the rules when they type in the string. Robust GUI code should do error checking to enforce this, but you would then end up writing a mini-parser. Whether the short-cut using regexprep and str2num is satisfactory depends on how public and sensitive the application is.

댓글 수: 3

Dr. Seis
Dr. Seis 2011년 12월 4일
I think that is a good idea. I would be more than happy to see how to switch the comma-dash-parenthetic-operator format to a colon-operator format.
Looks like this will turn about 40 lines of code into maybe 2 or 3.
David Young
David Young 2011년 12월 4일
OK, I'll put the regexp line in the question for better formatting.
Dr. Seis
Dr. Seis 2011년 12월 4일
This is most excellent. I am going to have to familiarize myself with this "regexp" stuff in order to increase efficiency with future code. Thanks, David!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2011년 12월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by