Separate numbers from text

조회 수: 30 (최근 30일)
Deepa Maheshvare
Deepa Maheshvare 2019년 9월 9일
댓글: Walter Roberson 2020년 2월 22일
I have the follwing character array
C = {'LAN310'}
{'SHA550'}
Expercted result:
C = [ 310 550]
From one of the answers posted in the previous posts, I tried the following
D = regexprep(C,'[\d"]','');
The above replaces the numbers with null, but I would like to replace characters with null. Any suggestions?

채택된 답변

Walter Roberson
Walter Roberson 2019년 9월 9일
편집: Walter Roberson 2019년 9월 9일
D = str2double( regexrep(C, '\D', '') );
Note that this will replace all + - . and e E d D used as exponents, and that if there are multiple numbers separated by non-numbers then this will jam them together.
Another approach is
D = str2double( C(ismember(C, '0':'9')) );

추가 답변 (1개)

madhan ravi
madhan ravi 2019년 9월 9일
편집: madhan ravi 2019년 9월 9일
C = str2double(regexprep(C,'[a-zA-Z^()]','')).'
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 2월 22일
There is a maxim in computer reliability and security engineering:
"Do not validate input by rejecting characters or patterns: only ever validate input by accepting characters or patterns that you know you can deal with."
When you work by rejecting things, then there is the possibility that you forgot to reject something, or that later some new method will be introduced that permits the user to slip new values past your validation. For example the pattern [a-zA-Z^()] does not reject & or ; or # or % so it would be happy to pass through A or %41 and a later step might do the translation to A or A .
There was a whole spate of security problems when unicode encoding was added to the HTML standard: code that validated by rejecting the old escape sequences stopped working when the libraries added a new escape sequence.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by