Div
Div

Reputation: 121

MATLAB: How to delete characters from 2x1 or nx1 string?

Good day.

Here I have a 2x1 string:

A = ["CHAPTER 1. Random info in middle one, Random info still continues. 1";...
     "CHAPTER 2. Random info in middle two. Random info still continues. 1"];

How can I remove "CHAPTER #", and the last number and space at the back of the space? Here is my attempt:

%PlanA
for n=1:2
% Delete "Chapter+Nr"
A(n,1) = erase(A,'(CHAPTER \d)'); 
% Delete last nr 1 at end
A(n,1) = erase(A,'\d'); 
end

%PlanB
A(strcmp(A, 'CHAPTER \d')) = []

I have no idea why this is not working?

Help is appreciated Thanks!

Upvotes: 0

Views: 143

Answers (1)

Paolo
Paolo

Reputation: 26074

You can use regexprep for this:

regexprep(A,'CHAPTER \d+\. (.+) \d$','$1')
ans = 

2×1 string array

"Random info in middle one, Random info still continues."
"Random info in middle two. Random info still continues."

Upvotes: 3

Related Questions