siegel
siegel

Reputation: 829

Selectively deleting commas and splitting strings

I have s string that looks like

txt = '"EMB","iShares J,P. Morg",110.81,N/A'

I'm using strsplit(txt,','); to break this into separate strings based on the comma delimiter. However I want to ignore the comma between the 'J' and the 'P', since it's not a delimiter; it's just part of the name.

Is there a way I can say "if a comma is between two quotes but there are other characters between the quotes, delete the comma"?

Upvotes: 1

Views: 110

Answers (2)

Eitan T
Eitan T

Reputation: 32930

Here's an equivalent regexp one-liner:

C = regexp(txt, '("[^"]*")|([^,"]+)', 'match')

The result is a cell array with already split strings. Unfortunately, I don't have MATLAB R2013, so I cannot benchmark this versus strsplit.

Upvotes: 2

Hugh Nolan
Hugh Nolan

Reputation: 2519

A silly (but functional) answer:

inquotes=false;
keep=true(1,length(txt));
for v=1:length(txt)
    if (txt(v)=='"')
        inquotes=~inquotes;
    elseif (txt(v)==',' && inquotes)
        keep(v)=false;
    end
end
txt=txt(keep);
tt=strsplit(txt,',');

This will, if you are in quotes, remove the commas so that you can use strsplit. That is what I understood you want to do, correct?

Upvotes: 1

Related Questions