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

。_饼干妹妹 提交于 2021-01-29 07:17:24

问题


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!


回答1:


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."


来源:https://stackoverflow.com/questions/64172466/matlab-how-to-delete-characters-from-2x1-or-nx1-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!