Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


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

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,380
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$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.



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

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.