-3

I have a [String] that goes like

ABC,JKL,123,12,PQR

ABC,"XY, Z",654,54,PQR

The resulting array should look like this:

["ABC","JKL","123","12",PQR],["ABC","XY, Z","654","54","PQR"]

This is what I have tried already, but this does not work as I want in second element's case:

content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",") }
Martin
  • 16,093
  • 1
  • 29
  • 48
KishanSadhwani
  • 118
  • 1
  • 9
  • 2
    That's great. What have you tried so far to accomplish this? – Martin Sep 27 '19 at 07:46
  • as of now I am using -> content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",") } , but this does not work as I want in second element's case – KishanSadhwani Sep 27 '19 at 07:56

1 Answers1

0

Idea behind solution:

You want to split your string into an array on every occurrence of ,, accounting for data contained within " as a single item.

To do this you have to use the global split function with a regex pattern.

Code sample:

extension String
{
  func splitCommas() -> [Stirng] {
    let pattern = ",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)" //regex pattern for commas that are not within quotes
    if let regex = try? NSRegularExpression(pattern: pattern, options: []) {
      let string = self as NSString
      return regex.matches(in:inputString, range: NSMakeRange(0, inputString.utf16.count)).map {
        string.substring(with: $0.range).replacingOccurrences(of: ",", with: "") //removing all instances of commas
      }
    }
    return []
  }
}

Hope this helps! ;)

Updates

Updated code to more modern example.

Also implemented function as a String extension for usability within all of the String variables.

ZektorH
  • 2,680
  • 1
  • 7
  • 20