MATLAB Answers

Help to solve a regexp problem

9 views (last 30 days)
I'm trying to capture comment block in a string (char array). Regular expression '%.*(\n|$)' captures string from % to the end of the line.
regexp(sprintf(' %%this is a comment'),'%.*(\n|$)','match')
ans =
'% this is a comment'
However, what I want to do is to capture multiple incidence of comment blocks in a char array. The above expression only captures the first one, failing to match '% and this'.
regexp(sprintf(' %%this is a comment\n %%and this\n'),'%.*(\n|$)','match')
ans =
'% this is a comment…'
Could somebody help me about this?
Kouichi C. Nakamura
Kouichi C. Nakamura on 8 Jul 2016
This looks really interesting. I'll surely give it a try. I could help me a lot. Thanks!

Sign in to comment.

Accepted Answer

per isakson
per isakson on 8 Jul 2016
Test this
>> str = sprintf(' %%this is a comment\n %%and this\n');
>> cac = regexp( str, '[ ]*%[^\n]+', 'match' )
cac =
' % this is a comment' ' % and this'
>> whos cac
Name Size Bytes Class Attributes
cac 1x2 294 cell
Guillaume on 8 Jul 2016
Note that your regular expression would have worked if you'd used the non-greedy *?:
regexp(sprintf(' %%this is a comment\n %%and this\n'),'%.*?(\n|$)','match')
Nonetheless, per's expression is probably more efficient.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!