search and replace exact substring

10 ビュー (過去 30 日間)
Notsure USA
Notsure USA 2014 年 10 月 8 日
コメント済み: Image Analyst 2014 年 10 月 9 日
Hello,
I am parsing a string to check for an exact phrase. If the exact phrase is found, then I want to replace the phrase with a new phrase. The problem is, sometimes the phrase will be part of anothe phrase. Example:
wish to change the phrase "eps" to "%eps"
str = 'steps = eps*100 + beta*steps*eps';
newStr = 'steps = %eps*100 + beta*steps*%eps';
I'm having trouble picking out the exact phrase; each parsing phrase that I've come up with always catches something undesired e.g. 'steps' => 'st%eps' etc.
I've tried things like: st1 = regexprep(str,'^\w*(?=eps)^\w*','%eps')
(where I think I'm saing, look around the phrase "eps", if there's no "word" in the regexp sense, then replace the phrase with "%eps", but I'm obviously not there yet.
TIA,
CDQ (R2011b)

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 10 月 8 日
編集済み: Azzi Abdelmalek 2014 年 10 月 8 日
str = 'steps = eps*100 + beta*steps*eps';
regexprep([' ' str ' '],'(?<=[^a-zA-Z])eps(?=[^a-zA-Z])','%eps')
  1 件のコメント
Notsure USA
Notsure USA 2014 年 10 月 8 日
This appears to solve my problem; thank you Azzi. I had (probably still have) a fundamental misunderstanding of the lookahead/lookbehind operators.

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2014 年 10 月 8 日
newString = strrep(oldString, ' eps', ' %eps');
  2 件のコメント
Notsure USA
Notsure USA 2014 年 10 月 8 日
Thank you for your answer; this was my original solution but unfortunately it doesn't catch one of the eps (the last one):
>> str = 'steps = eps*100 + beta*steps*eps';
>> newString = strrep(str, ' eps', ' %eps')
newString =
steps = %eps*100 + beta*steps*eps
Image Analyst
Image Analyst 2014 年 10 月 9 日
You could do it in two lines of code instead of one:
newString = strrep(oldString, ' eps', ' %eps');
newString = strrep(newString, '*eps', '%eps');
Likewise in the event you have any other symbols. Sorry for not doing this in the first place - thought you'd know. I find this much easier, and more straightforward and intuitive than trying to compose/invent complicated regexp expressions, so that's why I suggested it. Looks like you're quite adept with regexp though and can understand things like ' (?<=[^a-zA-Z])eps(?=[^a-zA-Z]) ', and that's great, because not everybody can.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by