Regular expression search in cell array of strings
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,cmd)
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]','inv'))
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'
引用
Maximilien Chaumon (2024). Regular expression search in cell array of strings (https://www.mathworks.com/matlabcentral/fileexchange/23993-regular-expression-search-in-cell-array-of-strings), MATLAB Central File Exchange. に取得済み.
MATLAB リリースの互換性
プラットフォームの互換性
Windows macOS Linuxカテゴリ
- MATLAB > Language Fundamentals > Data Types > Characters and Strings >
- MATLAB > Language Fundamentals > Data Types > Cell Arrays >
タグ
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!