3.0

3.0 | 2 ratings Rate this file 9 Downloads (last 30 days) File Size: 1.43 KB File ID: #23993

Regular expression search in cell array of strings

by Maximilien Chaumon

 

04 May 2009 (Updated 05 May 2009)

Search in cell array of strings. Returns indexes of cells in stead of indexes within cells .

| Watch this File

File Information
Description

The matlab original regexp function on cell arrays returns a cell array of the same size with result of regexp on each cell. Finding cells that match a particular pattern needs iteration over cells with a ~isempty query on each cell to figure out those that contain a match. Regexpcell does that for you and returns indexes of cells that contain a match to the pattern.

idx = regexpcell(c,pat,inv)
Return indices idx of cells in c that match pattern pat (regexp).
Invert if inv is true (optional).
pat can be char or cellstr. In the later case regexpcell returns the union of all matches (could have duplicates).

Examples:
Regexp on cell arrays returns a cell array the same size as the input containing indexes of match within each cell.
Imgs = {'ladder.tif','baby.tif','Scissors.tif','tree.tif','lamp_1.tif','arrow.tif','Telescope.tif','Whistle.tif','car2.tif','car1.tif','Fork.tif','screwdriver.tif','axe.tif','Guitar.tif','Keys.tif','Bike.tif','flower-coloring-pages00051im.tif','airplane1.tif';};
regexp(Imgs,'car')
ans =
  Columns 1 through 14
     [] [] [] [] [] [] [] [] [1] [1] [] [] [] []
  Columns 15 through 18
     [] [] [] []

Regexpcell retrieves indexes of cells matching the pattern.
regexpcell(Imgs,'car')
ans =
     9 10
So that you can directly use the output as index in the same cell and retrieve cells that match a pattern.
Imgs(regexpcell(Imgs,'car'))
ans =
    'car2.tif' 'car1.tif'

Invert the result if third argument is true.
Imgs(regexpcell(Imgs,'[c]',true))
ans =
  Columns 1 through 6
    'ladder.tif' 'baby.tif' 'tree.tif' 'lamp_1.tif' 'arrow.tif' 'Whistle.tif'
  Columns 7 through 12
    'Fork.tif' 'axe.tif' 'Guitar.tif' 'Keys.tif' 'Bike.tif' 'airplane1.tif'

MATLAB release MATLAB 7.5 (R2007b)
Tags for This File  
Everyone's Tags
cell, cell array, cellstr, find, regexp, regular expression, search, string
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (2)
06 May 2009 Maximilien Chaumon

I formatted it more accurately. I now explain how it is solving a problem faced when searching cells with regexp.

05 May 2009 Darren Rowland

This submission is poorly formatted. There should be a H1 line, examples of use and comments. Further, this functionality is already provided by regexp.

Updates
05 May 2009

I tell what the submission solves.
Documentation has examples of how I'm most of the time using it.
Comments inserted in the code.

Contact us