A question on regexprep

조회 수: 1 (최근 30일)
Edward Huang
Edward Huang 2019년 8월 19일
댓글: Edward Huang 2019년 8월 19일
This is a question stem from a Cody Problem when I looked through those efficient solutions. Let's say I have the following code:
s = 'John got an A in math.';
regexprep(s,'\<(\w)(\w*)(\w)\>','$1${$2(end:-1:1)}$3');
If I try to replace each match with only one of its tokens:
regexprep(s,'\<(\w)(\w*)(\w)\>','$1'); % or '$2','$3'
I will find that 'A' can be recognized as any one of them, and yet when it is replaced by '$1${$2(end:-1:1)}$3', only one copy of 'A' is returned. Why?
Thank you in advance.

채택된 답변

TADA
TADA 2019년 8월 19일
A is not a match for your regexp,
match = regexp(s,'\<(\w)(\w*)(\w)\>', 'match')
match =
1×5 cell array
{'John'} {'got'} {'an'} {'in'} {'math'}
so it's not replaced by anything,
  1. 'John' was replaced by 'ho'
  2. 'got' was replaced by 'o'
  3. 'an' was replaced by ''
  4. A is not a match, not replaced
  5. 'in' was replaced by ''
  6. 'math' was replaced by 'ta'
s2 = regexprep(s,'\<(\w)(\w*)(\w)\>','${$2(end:-1:1)}')
s2 =
'ho o A ta.'
  댓글 수: 1
Edward Huang
Edward Huang 2019년 8월 19일
Oops... I didn't realize I could have checked with regexp... Thanks!

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

추가 답변 (0개)

카테고리

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