The Math Forum

Search All of the Math Forum:

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

Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   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
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

In article <k48ap7$i72$>,
"Nasser M. Abbasi" <> wrote:

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

> > 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

> >
> -----------------
> 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
Make obvious changes to get real email address.

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.