Interpret string to form sequence of numbers

4 views (last 30 days)
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.

Accepted Answer

David Young
David Young on 4 Dec 2011
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 Comments
David Young
David Young on 4 Dec 2011
OK, I'll put the regexp line in the question for better formatting.
Dr. Seis
Dr. Seis on 4 Dec 2011
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!

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!