regexprep does not exactly what I want

조회 수: 2 (최근 30일)
hyble
hyble 2019년 10월 16일
댓글: hyble 2019년 10월 17일
Dear all,
I have the following cell array
Charge = {'OH-1'} {'KOH+0'} {'K+1'} {'I-1'} {'HI+0'} {'H3O+1'} {'H2O+0'}
I want to remove all information before the + and - signs. Therefore I tried the following:
regexprep(Charge,'[^-+].','');
which produces
{'-1'} {'0'} {'1'} {'1'} {'+0'} {'1'} {'0'}
This works well except in case of only one character in front of the minus sign (i.e. in case of I-1). In that case, the - sign is also deleted. The - signs are crucial to be included, the + signs not.
Any suggestions?
Thanks, Tim

채택된 답변

Daniel M
Daniel M 2019년 10월 16일
편집: Daniel M 2019년 10월 16일
There's definitely a way to do it using regexprep, but I found this solution first, so hopefully it is sufficient.
Charge = {'OH-1','KOH+0','K+1','I-1','HI+0','H3O+1','H2O+0'};
c = regexp(Charge,'[-+]\w*','match');
cc = cat(2,c{:}); % put back into cell array
  댓글 수: 6
Guillaume
Guillaume 2019년 10월 16일
The comment about the regexprep referred to the original question, not your answer.
I wrote most of my comment shortly after you posted your answer but had to dash off to a meeting before posting it. When I finally posted it, it was a bit out of date. Sorry about that.
hyble
hyble 2019년 10월 17일
Many thanks to all of you for helping out here!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2019년 10월 16일
편집: Stephen23 2019년 10월 16일
>> regexprep(Charge,'^[^-+]*','')
ans =
'-1' '+0' '+1' '-1' '+0' '+1'
>> regexp(Charge,'[-+].+$','once','match')
ans =
'-1' '+0' '+1' '-1' '+0' '+1'
  댓글 수: 1
Daniel M
Daniel M 2019년 10월 16일
This will handle edge cases better than my solution above. More robust.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by