필터 지우기
필터 지우기

regexprep help with replacing strings

조회 수: 1 (최근 30일)
tiwwexx
tiwwexx 2019년 7월 5일
댓글: Walter Roberson 2019년 7월 5일
Hey guys/girls,
I'm needing to replace some elements of a string and I'm using regexprep. What I have to replace is a number followed by a space followed by a letter. This must be replaced with the number and two enter signs then the letter. The example will be the best to get an idea of what I mean.
Say I have the string
'hello youre 15 years old'
I want to change this to be
'hello youre 15[\n\n]years old'
where the \n is an enter.
This must also work for any general 'number' 'space' 'letter' combination.
Thank you in advance!

채택된 답변

Walter Roberson
Walter Roberson 2019년 7월 5일
'(\d+)\s+([A-Za-z])', '$1\n\n$2'
  댓글 수: 2
tiwwexx
tiwwexx 2019년 7월 5일
You're awesome, thank you!
One more question. Do you know where this is in the documentation?
Walter Roberson
Walter Roberson 2019년 7월 5일
\d Any numeric digit; equivalent to [0-9]
\s Any white-space character; equivalent to [ \f\n\r\t\v]
[c1-c2] Any character in the range of c1 through c2
(expr) Group elements of the expression and capture tokens.
$N Nth token
Thus we capture a series of digits into the first token, then we match whitespace but do not capture it, then we capture a single letter. In replacement, we pull out the first captured token, then we output two newlines, then we output the second captured token.
There are other ways of phrasing this, such as
'(?<=\d)\s+\(?=[A-Za-z])', '\n\n'
This says to look for whitespace that has a digit before it and a letter after it, and change the whitepsace to \n\n

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by