Finding the indexes of multiple substrings within a larger string.

2 views (last 30 days)
I’m trying to find the indexes of all two digit pairs in a very long string of numbers, say “c”. I can easily find all occurrences of one string at a time; for example strfind(c, ’00’)…strfind (c, ’01’). But I want a way to do this for all sets one hundred sets; 00 to 99. I tried this:
x=0:99;
dig=sprintf('%02d ',x);
%converts the vector 0to99 into a string with two digits, space between numbers
dub_dig=strsplit(dig);
%splits each pair into cells
dub_dig_str=string(dub_dig);
%converts to a string
How do I get this sequence of strings (dub_dig_str) to work in something like a for loop using the strfind function? When I try this it crashes. I would like to output a matrix of indexes of where each pair occurs, for all pairs.
Thanks

Accepted Answer

Stephen23
Stephen23 on 24 Mar 2023
Edited: Stephen23 on 24 Mar 2023
idx = regexp(c,'\d\d') % no overlaps
idx = regexp(c,'\d(?=\d)') % with overlaps
  7 Comments
Steve
Steve on 1 Apr 2023
Thank you. This works. I must admit, as a beginner, some of the code looks cryptic (e.g., "@(a){a}", and the output of cells 'Z' is hard to work with mathematically, but I'm sure it's possible. I'm appreciating the tradeoffs between classic numerical functions and string approaches.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 24 Mar 2023
c = 'a91bb48353'
c = 'a91bb48353'
mask = ismember(c, '0':'9');
odd_pair = find(mask(1:2:end-1) & mask(2:2:end)) * 2 - 1
odd_pair = 1×2
7 9
even_pair = find(mask(2:2:end-1) & mask(3:2:end)) * 2
even_pair = 1×3
2 6 8
pair_starts_at = union(odd_pair, even_pair)
pair_starts_at = 1×5
2 6 7 8 9
  2 Comments

Sign in to comment.

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!

Translated by