Filter löschen
Filter löschen

regexprep help with replacing strings

1 Ansicht (letzte 30 Tage)
tiwwexx
tiwwexx am 5 Jul. 2019
Kommentiert: Walter Roberson am 5 Jul. 2019
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!

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by