complex string match with regexprep

1 view (last 30 days)
S H
S H on 14 May 2019
Commented: Adam Danz on 14 May 2019
What should be the expression in the following script to generate out from str?
str='diff([v0(k-1,2)-v0(k-1,1) v(2)-v(1)])/diff(t0(k-1:k))+((v(2)-0)*diff(t0(k-1:k))+sum((v0(2:k-1,2)-v0(2:k-1,10)).*diff(t0(1:k-1)).'',1))';
expression = ???;
replace = '0';
out=regexprep(str,expression,replace);
out='diff([v0(k-1,2)-v0(k-1,1) v(2)-v(1)])/diff(t0(k-1:k))+((v(2)-0)*diff(t0(k-1:k))+sum((v0(2:k-1,2)-0).*diff(t0(1:k-1)).'',1))'
  7 Comments
S H
S H on 14 May 2019
I tested your answer on my lengthy strings and it works as expected. Thank you for teaching me the use of [^,]* in regexprep. I was reading Matlab regexp help page a few times and such an important and helpful combination as [^,]* is not clearly explained there.
Adam Danz
Adam Danz on 14 May 2019
There are so many options with regular expressions that it's hard to capture them all in one document. I usually just google awkward phrases like "regular expressions match any character until" to remind myself of the options. The website I suggested in my answer is another great tool.

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 14 May 2019
Edited: Adam Danz on 14 May 2019
Here you are.
str='diff([v0(k-1,2)-v0(k-1,1) v(2)-v(1)])/diff(t0(k-1:k))+((v(2)-0)*diff(t0(k-1:k))+sum((v0(2:k-1,2)-v0(2:k-1,10)).*diff(t0(1:k-1)).'',1))';
expression = 'v0\([^,]+,10\)';
replace = '0';
out = regexprep(str, expression, replace)
Compare input/output (I added space in output for comparison)
diff([v0(k-1,2)-v0(k-1,1) v(2)-v(1)])/diff(t0(k-1:k))+((v(2)-0)*diff(t0(k-1:k))+sum((v0(2:k-1,2)-v0(2:k-1,10)).*diff(t0(1:k-1)).',1)) %input
diff([v0(k-1,2)-v0(k-1,1) v(2)-v(1)])/diff(t0(k-1:k))+((v(2)-0)*diff(t0(k-1:k))+sum((v0(2:k-1,2)-0 ).*diff(t0(1:k-1)).',1)) %output
  2 Comments
S H
S H on 14 May 2019
It works nicely. Thank you very much.
Adam Danz
Adam Danz on 14 May 2019
Edited: Adam Danz on 14 May 2019
Great! Just so you know...
  • v0\( Start the expression at v0(
  • [^,]+ Stop matching just before the next comma
  • ,10\) make sure the expression ends with ,10)
A nice workstation to develop regular expressions: https://regex101.com/

Sign in to comment.

More Answers (0)

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!