Method to GREEDILY select an optional text using regular expressions?

2 visualizaciones (últimos 30 días)
Ana Alonso
Ana Alonso el 19 de Nov. de 2018
Editada: Stephen23 el 13 de Sept. de 2019
I'm trying to pick out the name of some folders in a directory, and each have slightly variable names. The names of the folders are:
UD_epoch
UD_Epoch
epoch
Epoch
UD_epoch1
UD_Epoch2
Right now the regular expression I'm using to pick out these folders is:
regexp(nfolders, '(UD.?(e|E)poch\d?)','match')
This picks out the first four folders successfully, but returns the last two as 'UD_epoch' & 'UD_Epoch.' How do I specify that I want the optional element to be included?
Thanks!

Respuestas (1)

per isakson
per isakson el 13 de Sept. de 2019
Editada: per isakson el 13 de Sept. de 2019
Try
%%
nfolders = {
'UD_epoch'
'UD_Epoch'
'epoch'
'Epoch'
'UD_epoch1'
'UD_Epoch2'
};
%%
cac = regexp( nfolders, '^(UD_)?(e|E)poch\d?$', 'match' );
it returns
>> cac{:}
ans =
1×1 cell array
{'UD_epoch'}
ans =
1×1 cell array
{'UD_Epoch'}
ans =
1×1 cell array
{'epoch'}
ans =
1×1 cell array
{'Epoch'}
ans =
1×1 cell array
{'UD_epoch1'}
ans =
1×1 cell array
{'UD_Epoch2'}
>>
/R2018b
  2 comentarios
Stephen23
Stephen23 el 13 de Sept. de 2019
Editada: Stephen23 el 13 de Sept. de 2019
+1 With the 'once' option makes the outputs easier to work with (no nested cell arrays):
>> regexp( nfolders, '(UD_)?[eE]poch\d*', 'match' ,'once')
ans =
'UD_epoch'
'UD_Epoch'
'epoch'
'Epoch'
'UD_epoch1'
'UD_Epoch2'

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by