Azzera filtri
Azzera filtri

regexprep help with replacing strings

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by