Method to GREEDILY select an optional text using regular expressions?

2 次查看(过去 30 天)
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!

回答(1 个)

per isakson
per isakson 2019-9-13
编辑:per isakson 2019-9-13
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 个评论
Stephen23
Stephen23 2019-9-13
编辑:Stephen23 2019-9-13
+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'

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by