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