String parsing advice...

  • HI. I have a string I need to parse which is a comma separated list of variously typed elements... eg.

    "1,0.25,'Hello, this is a string','each\nstring\non\na\mnewline',45,'He said ''hello'' to me',0"

    What I want is to split the string up into an NSArray of NSString objects, which I can then enumerate through and process one by one.

    I've tried using the NSString method 'componentsSeparatedByString' and using a comma as the separator, but that splits string elements if they have a comma in them...eg:

    1
    0.25
    'Hello
    this is a string'
    etc...

    I have also tried adding brackets around the source string and separating the elements using the 'propertyList' method, but this seems to get confused by the newline codes ('\n") embedded in string elements.

    Before I start coding up my own parsing method which can deal with these problems is there anything in the Cocoa API which would parse my strings robustly - ie deal with string elements which have embedded newline and comma characters in them ?

    Thanks.
  • > HI. I have a string I need to parse which is a comma separated list
    > of variously typed elements... eg.

      .... so you're looking for a CSV (comma separated value) parser?

    http://www.google.com/search?client=safari&rls=en-us&q=csv+parser&a
    mp;ie=UTF-8&oe=UTF-8


      There are plenty of examples out there that correctly handle
    situations where separators/delimiters are inside quotes, etc.

    --
    I.S.
  • On 12 Dec 2007, at 12:11, I. Savant wrote:

    >> HI. I have a string I need to parse which is a comma separated list
    >> of variously typed elements... eg.
    >
    > .... so you're looking for a CSV (comma separated value) parser?
    >
    > http://www.google.com/search?client=safari&rls=en-us&q=csv+parser&a
    mp;ie=UTF-8&oe=UTF-8

    >
    > There are plenty of examples out there that correctly handle
    > situations where separators/delimiters are inside quotes, etc.

    More pertinently, there are plenty of Cocoa implementations already:

      <http://www.google.co.uk/search?hl=en&q=cocoa+csv>

    Not that coding such a parser is difficult anyway, especially using
    NSScanner and NSCharacterSet.

    Kind regards,

    Alastair.

    --
    http://alastairs-place.net
previous month december 2007 next month
MTWTFSS
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Go to today