I need to export from a cell array the char 'CL'; the problem is that I also have the 'CL/imp' chars in the array. I tried using the command regexp(str​,'CL','mat​ch'), but it takes also the from the strings containing 'CL/imp'. What should I do?

1 view (last 30 days)
str='CL,EXAMPLE,CL/imp,example2';
% I just need to export 'CL', not 'CL/imp'
ans=regexp(str,'CL','match')
ans= 'CL' 'CL'

Accepted Answer

Stephen23
Stephen23 on 24 Nov 2017
>> C = regexp(str,',','split');
>> C{strcmp('CL',C)}
ans = CL
  14 Comments
Stephen23
Stephen23 on 27 Nov 2017
Edited: Stephen23 on 27 Nov 2017
Perhaps this:
>> str = 'CL';
>> [mtc,idx] = regexp(str,'CL(?=($|[^A-Z/_]))','match','start','once')
mtc = CL
idx = 1
It would help a lot if you actually accurately specified what you want to match, or perhaps more usefully what you do NOT want to match.
Alcapalb
Alcapalb on 28 Nov 2017
Thank you very much, Stephen. It works, now. Sometimes "beginners" might be not clear when they try to expose their problems.

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 26 Nov 2017
Edited: Guillaume on 27 Nov 2017
Alcapalb, what Stephen is asking is a clear definition of what need to be matched and what must be rejected as well as what are the boundaries for whatever you want to match. We can make regular expressions match almost anything and reject almost anything but the rules need to be exactly defined.
For example, you can write
matches = regexp(str, 'CL(?!/imp)', 'match')
That would not match 'CL' in 'CL/imp' so would answer your question. However, it still would match 'CL' in 'CL/abc' and in 'abcCLdef' and in 'CLimp', etc. No idea if that's what you want because you haven't clearly defined what is allowed and not allowed.
Perhaps you don't want 'CL' followed by a '/', in which case we change the regular expression to
matches = regexp(str, 'CL(?!/)', 'match')
No more 'CL/abc' but it is still matching 'abcCLdef'.
Perhaps what you want to match is instead
matches = regexp(str, '(?<=^|[^a-zA-Z])CL(?=$|[^a-zA-Z])', 'match')
This would match 'CL' as long as it's preceded by the start of the string or a non-letter and as long as it's followed by the end of the string or a non-letter. A completely different set of rules that results in a completely different regular expression.
All of these could be the answer to your question or it could be something completely different because you haven't specified.
Furthermore, in your question you're asking for the 'match' which is a bit pointless as it's always going to be 'CL'. So there's probably something more about that you've also not stated.
Finally, don't use ans as a variable as it's a special variable that matlab is likely to overwrite.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!