regexprep help with replacing strings
1 回表示 (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
採用された回答
Walter Roberson
2019 年 7 月 5 日
'(\d+)\s+([A-Za-z])', '$1\n\n$2'
2 件のコメント
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 Center および File Exchange で Get Started with MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!