Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: What is the best way to replace certain characters in a string?
Replies: 4   Last Post: Sep 30, 2012 9:50 AM

 Messages: [ Previous | Next ]
 Doug Schwarz Posts: 1,412 Registered: 12/7/04
Re: What is the best way to replace certain characters in a string?
Posted: Sep 29, 2012 11:10 PM

In article <k48ap7\$i72\$1@speranza.aioe.org>,
"Nasser M. Abbasi" <nma@12000.org> wrote:

> On 9/29/2012 9:07 PM, Daniel wrote:
> > Hello everyone,
> >
> > I have a cell array of strings (each cell contains one string).

[snip]
> > Now say I want to replace all the "dog" with "cat". In each string,
> >the word "dog" occurs at most once. So I do the following

[snip]
> >
>
> -----------------
> c=cellfun(@(x) regexprep(x,'dog','cat'), a,'UniformOutput' ,false);
> celldisp(c)
> -----------------
>
> c{1} =
> I like cats.
>
> c{2} =
> I have three cats.
>
> c{3} =
> One of the cats is yellow.
>
> --Nasser

regexprep is vectorized. Also, if you want to match only the whole word
"dog" and not match "dog" in, say, "dogged pursuit", then use \< and \>:

>> a = {'my dog has fleas','dogged pursuit','horse, dog, pig'};
>> b = regexprep(a,'\<dog\>','cat')

b =
'my cat has fleas' 'dogged pursuit' 'horse, cat, pig'

If you really just want to replace ALL instances of "dog" with "cat" then

>> b = strrep(a,'dog','cat')
b =
'my cat has fleas' 'catged pursuit' 'horse, cat, pig'

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.

Date Subject Author
9/29/12 Daniel
9/29/12 Nasser Abbasi
9/29/12 Doug Schwarz
9/29/12 Daniel
9/30/12 dpb