regexprep help with replacing strings

1 view (last 30 days)
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!

Accepted Answer

Walter Roberson
Walter Roberson on 5 Jul 2019
'(\d+)\s+([A-Za-z])', '$1\n\n$2'
  2 Comments
tiwwexx
tiwwexx on 5 Jul 2019
You're awesome, thank you!
One more question. Do you know where this is in the documentation?
Walter Roberson
Walter Roberson on 5 Jul 2019
\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

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!