简体   繁体   中英

Matlab regexp command not working as intended

f =  dir('../Data/PML*.mat');
f1 = regexp({f.name}, 'PML*.mat', 'match');
[f1{:}]

This is the snippet of my code to select files in the Data folder residing in the parent directory. The f is a structure array of 66 elements(There are 66 files there) as expected and out of these I want to select files which have a filename as follows: PMLsigma_8PMLkappa_6.mat . However the result of these operations is an empty cell array and I have no idea it results in an empty array. If instead of 'PML*.mat' on the second line -in the definition of f1- I write the full file name then there are no problems. What am I doing wrong here?

EDIT : First two elements of {f.name} cell array

r =

'PMLsigma_10PMLkappa_1.mat'    'PMLsigma_10PMLkappa_2.mat'

I would suggest going through MATLAB's regexp documentation again, paying particular attention to the expression portion.

Your regex expression 'PML*.mat' is attempting to match files that follow the below criteria:

  1. ( PM ) Match PM exactly
  2. ( L* ) Match L between 0 and unlimited times
  3. ( . ) Match any single character
  4. ( mat ) Match mat exactly

Matching strings include: PML.mat , PMkmat , and PMLLLLLLLLLLLLLLL.mat

One functional alternative could be 'PML.*\\.mat' , which operates as follows:

  1. ( PML ) Match PML exactly
  2. ( .* ) Match any character between 0 and unlimited times
  3. ( \\. ) Match . exactly ( \\ is an escape character )
  4. ( mat ) Match mat exactly

As an aside, if you're already filtering the results in your dir call, why do you need regexp ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM