1

Is there an equivalent function to strmatch that returns the numeric index of all array elements that begin with the specified regular expression (instead of string ?

Background: I've got an array of strings called strarray. I want to filter out all the strings that do NOT have a specific strprefix. The following code that looks for indexes of an array of strings (strmatch func) for which a particular prefix exists, and then builds new array from the lines that contain the prefix:

indexes = [];
n = strmatch(strprefix, strarray);
indexes = [indexes,n];
indexes = sort(indexes);
newarray = strarray(indexes);

It works OK, however the prefix is a string and I'd like to use defined regular expression instead.

Or perhaps there's an easier way (one liner?) to do such task ?


Update

I am aware of the regexp function. I am trying to filter out strings from an array of string, but I struggle to do it in one or two steps. My current code to do this (not sure if it's the correct Matlab way of coding).

  • Step 1. Empty the string with no prefix: regexp(strarray,[prefix,'.*'],'match','once');
  • Step 2. Get index of empty lines emptyCells = cellfun(@isempty,array);
  • Step 3. Remove the empty rows array(emptyCells) = [];

2 Answers 2

2

You really solved your problem yourself, but here is how you would do everything you say in a single (long) line. Note - I am assuming your prefix string starts with ^ so it properly matches "the start of the string" (if indeed that is what you want to do). Other question - unless all strings in strarray are the same length, you really should be using a cell array. In which case your Step 3 doesn't remove the string, it just sets it to []. I therefore suggest changing the logic so you "include all the good strings" in your output, rather than deleting the bad ones. That makes it look as follows:

strippedArray = strarray(~cellfun('isempty',regexp(strarray,[prefix,'.*'],'match','once')));

This worked for me...

Sign up to request clarification or add additional context in comments.

Comments

1

The function REGEXP allows you to match strings using regular expressions.

If you need help constructing or applying your regular expression, you may want to post additional detail.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.